Title Description:
Enter a list to output the last K nodes in the linked list.
Ideas:
First check the legitimacy of the parameters, Head==null or the number of nodes less than K directly return NULL.
Let head advance k-1 step, ans points to the head node, then head forward one step, ans also step forward. When the head reaches the last node, ans points to the reciprocal K-node. Time complexity O (n).
Solve:
1 /*2 Public class ListNode {3 int val;4 ListNode next = null;5 6 listnode (int val) {7 this.val = val;8 }9 }*/Ten Public classSolution { One PublicListNode Findkthtotail (ListNode head,intk) { A -ListNode ans =head; - the if(Head = =NULL|| K < 1) { - return NULL; - } - inti =K; + //head forward first k-1 node - while(i > 1 && head.next! =NULL) { +Head =Head.next; Ai--; at } - //Insufficient number of nodes - if(I! = 1) { - return NULL; - } - in while(Head.next! =NULL) { -Head =Head.next; toAns =Ans.next; + } - the returnans; * $ }Panax Notoginseng}
High-quality code-the penultimate K-node in a linked list