Home  >  Article  >  Backend Development  >  Sharing the method of implementing circular linked list in PHP

Sharing the method of implementing circular linked list in PHP

黄舟
黄舟Original
2017-09-16 09:06:211258browse

This article mainly introduces the implementation method of PHP circular linked list, and analyzes the definition, creation and traversal of PHP circular linked list and other operating techniques and precautions in the form of specific examples. Friends in need can refer to this article

The example describes the implementation method of PHP circular linked list. Share it with everyone for your reference, the details are as follows:

A circular linked list is a linked storage structure, similar to a singly linked list. The difference is that the tail node of the circular linked list points to the head node.

Thus forming a ring,

The ring linked list is a very flexible storage structure that can solve many practical problems, such as the magician's card dealing problem and the Joseph problem

Use a circular linked list to solve the problem. The following is a complete circular linked list example, implemented using PHP (refer to Teacher Han Shunping's PHP algorithm tutorial)


/** 
 *  环形链表的实现
 *  
 */
class child
{
  public $no;//序号
  public $next;//指向下个节点的指针
  public function __construct($no=''){
    $this ->no = $no;
  }
}
/**
 * 创建一个环形链表
 * @param $first null  链表的头节点
 * @param $num  integer 需要添加节点的数量
 */
function create(&$first,$num)
{
  $cur = null;
  for ($i=0;$i<$num;$i++)
  {
    $child = new child($i+1);
    if ($i==0)
    {  
      $first = $child;
      $first->next = $first;//将链表的尾节点指向头节点 形成环形链表
      $cur = $first;//链表的头节点不能动 需要交给一个临时变量
    } else {
      $cur->next = $child;
      $cur->next->next = $first;//将链表的尾节点指向头节点 形成环形链表
      $cur = $cur->next;
    }
  }
}
/**
 * 遍历环形链表
 * @param $first object 环形链表的头
 * 
 */
function show ($first)
{
  //头节点不能动,交个一个临时变量
  $cur = $first;
  while ($cur->next!=$first)//当$cur->next==$first说明到了链表的最后一个节点
  {
    echo $cur->no.&#39;</br>&#39;;
    $cur = $cur->next;
  }
  //当退出循环的时候$cur->next=$first 刚好会忽略当前节点本身的遍历 所以退出的时候还要输出一下 否则会少遍历一个节点
  echo $cur->no;
}

The above is the detailed content of Sharing the method of implementing circular linked list in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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