循环链表
Posted zh718594493
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了循环链表相关的知识,希望对你有一定的参考价值。
class Node{ public $data=null; public $next = null; public function __construct($data=null){ $this->data = $data; } } class LinkdList{ public $header=null; public function __construct($data=null){ $this->header= new Node(); } //插入 public function insert($data){ $current = $this->header; $newNode = new Node($data); while($current->next){ if($current->next != $this->header){ $current = $current->next; }else{ break; } } $current->next = $newNode; $newNode->next = $this->header; } //查找所在位置 public function find($data){ $current = $this->header->next; $index=1; while($current){ if($current->data == $data){ break; }else{ $index++; $current = $current->next; } } return $index; } //固定位置修改 public function update($data,$num){ $current = $this->header->next; $index=1; while($index < $num ){ $current = $current->next; $index++; } $current->data=$data; } //添加 public function add($data,$num){ $current = $this->header->next; $index=1; $newNode = new Node($data); while($index < $num){ $prev = $current; $current=$current->next; $index++; } $prev->next = $newNode; $newNode->next = $current; } //删除 public function del($num){ $current = $this->header->next; $index = 1; while($index < $num){ $prev = $current; $current = $current->next; $index++; } $prev->next = $current->next; } //遍历 public function listLink(){ $current=$first = $this->header; while($current){ $current = $current->next; if($current == $first){ break; } echo $current->data; echo " "; } } } //$arr=[10,304,4,5,1,30]; $arr=[10,304,4,5,1,30,38]; $obj = new LinkdList(); foreach ($arr as $key => $value) { $obj->insert($value); } //$obj->update(100,2); //$obj->add(90,4); //echo $obj->find(5); $obj->del(4); $obj->listLink();
以上是关于循环链表的主要内容,如果未能解决你的问题,请参考以下文章