List of the last K nodes in the list of topics description
Enter a list to output the last K nodes in the linked list.
Ideas
- The linked list is traversed with two pointers, and two pointers are separated by K nodes, and the pointer to the first step goes to the K-node when it is finished.
- Some points to be aware of
- Linked list may be empty, return null
- K value may be 0, return null
- The node of the linked list may not be enough k to return null
Code
/*PublicClass ListNode {int Val; ListNodeNext =Null ListNode (int val) {this.val = val;}} */PublicClass Solution {Public ListNode Findkthtotail (ListNode head,int k) {if (head = =null | | K = =0) {returnnull;} ListNoderight = head;for (int i =0; i < K-1; i++) {if (right. next! = null) {right = right. next;} else {return null;}} ListNode left = Head; while (right. Next! = null) {left = left.next; right = right. Next;} return left;}
List of the last K nodes in the list-Sword point offer