Detailed explanation of the steps to obtain the nodes of the linked list from back to front in PHP

php中世界最好的语言
Release: 2023-03-26 22:28:02
Original
1474 people have browsed it

This time I will bring you a detailed explanation of the steps for PHP to get the nodes of the linked list from back to front. What are the precautions for PHP to get the nodes of the linked list from back to front. Here is a practical case, let’s take a look. take a look.

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

<?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;
}
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the steps to operate mongoDB database with tp5 (thinkPHP5)

Why there is a problem with PHP Class SoapClient not found And the solution

The above is the detailed content of Detailed explanation of the steps to obtain the nodes of the linked list from back to front in PHP. 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