Home > Backend Development > PHP Tutorial > How to output the k-th node from the bottom of the linked list in PHP (code example)

How to output the k-th node from the bottom of the linked list in PHP (code example)

不言
Release: 2023-04-04 07:14:01
Original
1399 people have browsed it

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.

<?php
class Node{
        public $data;
        public $next;
}
//创建一个链表
$linkList=new Node();
$linkList->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);
Copy after login

object(Node)#10 (2) {
  ["data"]=>  string(4) "aaa9"
  ["next"]=>  object(Node)#11 (2) {
    ["data"]=>    string(5) "aaa10"
    ["next"]=>    NULL
  }
}
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template