Method for PHP to get the penultimate K node in linked list

  • 2021-08-31 07:33:54
  • OfStack

In this paper, the method of obtaining the penultimate K node in the linked list by PHP is described as an example. Share it for your reference, as follows:

Problem

Enter 1 linked list and output the penultimate k nodes in the linked list.

Solutions

Note that the topic is return nodes, not return values. The return value can be stored on the stack. Returning nodes cannot do this.

Set two pointers, and let the first pointer move k-1 times first. Then the two pointers move at the same time. When the first pointer reaches the last node, the second pointer is at the penultimate k node.

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;
}

For more readers interested in PHP related contents, please check the topics of this site: "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "php String (string) Usage Summary", "PHP Array (Array) Operation Skills Complete Book", "PHP Common Traversal Algorithms and Skills Summary" and "PHP Mathematical Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: