Algorithm 1]
Assume that a single-chain table has n nodes. If the last node is the reciprocal 1st nodes, the first n nodes are positive, and the corresponding relationship is (reciprocal => positive number ):
- 1 => N
- 2 => n-1
- 3 => N-2
- K => n-k + 1
Then, the number of the last K nodes is changed to the number of n-k + 1 nodes. First, we need to know how many nodes are there (traverse once) and find the forward n-k + 1 node (traverse again). The total time complexity is O (2n ).
Algorithm 2]
Set two pointers, Pa and Pb, to point at the same time to the header node. The PA pointer first moves the K-1 step, and then the two pointers move forward step by step at the same time. When the PA pointer reaches the end node, the PB Pointer Points to the nearest K node. This algorithm only uses a time series table. The time complexity is O (n ).
Algorithm 3]
The chain table is reversed. At this time, the End Node becomes the first node (traverse once), and then the K node can be searched from the first node (traverse again). The time complexity is O (2n ).