Welcome reprint, Reproduced Please be sure to indicate the source: http://blog.csdn.net/alading2009/article/details/45037001
Question 13th: Enter a one-way list to output the penultimate K-node in the linked list. The bottom No. 0 node of the list is the tail pointer of the linked list.
Consider how to keep k this information in the program execution, here to use two coordinates, to let the two coordinates between the k distance, so the current one coordinates reach the tail pointer, the latter coordinate exactly with the tail distance from the K nodes.
Code
Packagetest013;Importtest007. Node;/** * Created by CQ on 2015/4/11. * Question 13th: Enter a one-way list to output the penultimate K-node in the list. The bottom No. 0 node of the list is the tail pointer of the linked list. */ Public class Test013 { Public StaticNodeGetlastknode(Node list,intK) {if(List = =NULL|| K <0){return NULL; } Node anchor = list;intindex =0; while(List! =NULL){//anchor the distance between the K nodes and the list. if(Index < k) {list = List.getnext (); index++;Continue; } anchor = Anchor.getnext (); List = List.getnext (); }//// list length less than k//if (Index < k) {//anchor = NULL;// } returnAnchor } Public Static void Main(string[] args) {Node list =NewNode (5); Node node4 =NewNode (4); Node Node3 =NewNode (3); Node Node2 =NewNode (2); Node Node1 =NewNode (1); List.setnext (NODE4); Node4.setnext (NODE3); Node3.setnext (Node2); Node2.setnext (Node1); System.out.println ("The 2nd node of the bottom is:"+getlastknode (list,2). GetData ()); System.out.println ("The 4th node of the bottom is:"+getlastknode (list,4). GetData ()); System.out.println ("The 7th node of the bottom is:"+getlastknode (list,7). GetData ()); System.out.println ("The 10th node of the bottom is:"+getlastknode (list,Ten). GetData ()); }}
Execution results
tothe‘127.0.0.1:2218‘‘socket‘倒数第2个结点是:2倒数第4个结点是:4倒数第7个结点是:5倒数第10个结点是:5fromthe‘127.0.0.1:2218‘‘socket‘with0
Question 13th: List of the countdown K nodes in the list