This article mainly introduces the method of PHP to get the countdown K node in the chain list, involving PHP's traversal, judgment and other related operation skills, the friend who is interested in PHP can refer to this article
Problem
Enter a list to output the last K nodes in the linked list.
Solution Ideas
Note that this topic is the return node, not the return value. The return value can be stored with a stack. The return node cannot do so.
Set two pointers so that the first pointer moves k-1 times. Then the two pointers move at the same time, and when the first pointer reaches the last node, the second pointer is at the bottom of the K-node.
Note the boundary: the K length may exceed the list length, so when the first pointer's next is empty, 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;}
The above is all the content of this article, I hope to learn from you to provide help!!