Title Description
Enter a list to output the last K nodes in the linked list.
Public classTest {classListNode {intvalue; ListNode Next; PublicListNode (intvalue) { This. Value =value; } } Public Static voidMain (string[] args) {Test T=NewTest (); ListNode Node1= T.NewListNode (1); ListNode Node2= T.NewListNode (2); ListNode Node3= T.NewListNode (3); ListNode Node4= T.NewListNode (4); ListNode Node5= T.NewListNode (5); ListNode Node6= T.NewListNode (6); ListNode Node7= T.NewListNode (7); Node1.next=Node2; Node2.next=Node3; Node3.next=Node4; Node4.next=Node5; Node5.next=Node6; Node6.next=Node7; Node7.next=NULL; ListNode Kthnode= T.findkthtotail (Node1, 2); System.out.println (Kthnode.value); } /*** One traversal to find the bottom k node *@paramHead *@paramk K starting from 1 *@return */ PublicListNode Findkthtotail (ListNode head,intk) {//the list entered cannot be empty, K is greater than 0:k starting from 1, less than 0 is meaningless if(Head = =NULL|| K <= 0)return NULL; ListNode Pforward=Head; ListNode Pbehind=NULL; //The first pointer moves forward k-1. for(inti=0; i<k-1; i++) { //if K is greater than the number of nodes, next May point to NULL, return null if(Pforward.next = =NULL) return NULL; Pforward=Pforward.next; } //The second pointer does not move temporarilyPbehind =Head; //Two pointers move together//when the previous pointer traverses to the last node, a pointer to the bottom of the K-node while(Pforward.next! =NULL) {Pforward=Pforward.next; Pbehind=Pbehind.next; } returnPbehind; }}
Sword refers to the penultimate node of the offer-chain list