Home > Web Front-end > JS Tutorial > body text

PHP method to get the Kth node from the last in the linked list. Example sharing

小云云
Release: 2018-01-19 09:28:39
Original
1352 people have browsed it

This article mainly introduces the method of PHP to obtain the Kth node from the last in the linked list, which involves PHP's traversal, judgment and other related operating skills for the linked list. Friends who need it can refer to it. I hope it can help everyone.

Question

Input a linked list and output the k-th node from the last in the linked list.

Solution ideas

Note that this question returns nodes, not values. The return value can be stored on the stack. This cannot be done with return nodes.

Set two pointers, first move the first pointer k-1 times. Then the two pointers move at the same time. When the first pointer reaches the last node, the second pointer is at the k-th node from the bottom.

Note the boundary: the length of K may exceed the length of the linked list, so when the next of the first pointer is empty, null is returned

Implementation code


##

<span style="font-size: 14px;"><?php<br/>/*class ListNode{<br/> var $val;<br/> var $next = NULL;<br/> function __construct($x){<br/>  $this->val = $x;<br/> }<br/>}*/<br/>function FindKthToTail($head, $k)<br/>{<br/> if($head == NULL || $k ==0)<br/>  return NULL;<br/> $pre = $head;<br/> $last = $head;<br/> for($i=1; $i<$k; $i++){<br/>  if($last->next == NULL)<br/>   return NULL;<br/>  else<br/>   $last = $last->next;<br/> }<br/> while($last->next != NULL){<br/>  $pre = $pre->next;<br/>  $last = $last->next;<br/> }<br/> return $pre;<br/>}<br/></span>
Copy after login

Related recommendations:

DOM introduction and nodes, attributes, and search nodes

Detailed explanation of PHP implementation to find the entry node instance of the ring in the linked list

JQuery node traversal method summary

The above is the detailed content of PHP method to get the Kth node from the last in the linked list. Example sharing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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