The content of this article is about how PHP implements the k-th node from the bottom of the output linked list (code example). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .
Input a linked list and output the k-th node from the last in the linked list. The first pointer takes (k-1) steps to reach the k-th node. The two pointers move backward at the same time. When the first node reaches the end, the second node is located at the k-th node from the bottom.
next=null; $temp=$linkList; for($i=1;$i<=10;$i++){ $node=new Node(); $node->data="aaa{$i}"; $node->next=null; $temp->next=$node; $temp=$node; } //输入一个链表,输出该链表中倒数第k个结点。 function find($linkList,$k){ //速度快的指针 $fast=$linkList; //速度慢的指针 $slow=$linkList; //快指针先移动k-1步 for($i=0;$i<$k-1;$i++){ $fast=$fast->next; } if($fast->next==null){ return false; } //快慢指针一块移动 while($fast->next!=null){ $fast=$fast->next; $slow=$slow->next; } return $slow; } $knode=find($linkList,2); var_dump($knode);
object(Node)#10 (2) { ["data"]=> string(4) "aaa9" ["next"]=> object(Node)#11 (2) { ["data"]=> string(5) "aaa10" ["next"]=> NULL } }
Related recommendations:
PHP Get the countdown in the linked list Method of the Kth node
php example code to implement a singly linked list_PHP tutorial
The above is the detailed content of How to output the k-th node from the bottom of the linked list in PHP (code example). For more information, please follow other related articles on the PHP Chinese website!