PHP method for obtaining the last K nodes in the linked list, node
This example describes how PHP can obtain the last K nodes in a linked list. We will share this with you for your reference. The details are as follows:
Problem
Enter a linked list and output the last k nodes in the list.
Solution
Note that this question is to return the node rather than the return value. Stack can be used to store the returned values. You cannot do this if the node is returned.
Set two pointers to let the first pointer move the K-1 first. Then the two pointers move at the same time. When the first pointer reaches the last node, the second pointer is at the last k node.
Note: The length of K may exceed the length of the linked list. Therefore, if the next of the first pointer is null, null is returned.
Implementation Code
<? Php/* class ListNode {var $ val; var $ next = NULL; function _ construct ($ x) {$ this-> val = $ x ;}} */function FindKthToTail ($ head, $ k) {if ($ head = NULL | $ k = 0) return NULL; $ pre = $ head; $ last = $ head; for ($ I = 1; $ I <$ k; $ I ++) {if ($ last-> next = NULL) return NULL; else $ last = $ last-> next;} while ($ last-> next! = NULL) {$ pre = $ pre-> next; $ last = $ last-> next;} return $ pre ;}