链表: http://data.biancheng.net/view/160.html
双向链表: http://data.biancheng.net/view/166.html
双向链表
官方类:
https://www.php.net/manual/zh/class.spldoublylinkedlist.php
链表
class Node{
public $data;
public $next;
public function __construct($data = null, $next = null){
$this->data = $data;
$this->next = $next;
}
}
class LinkedList{
public $head;
public $size = 0;
//获取链表长度
public function getLength() {
return $this->size;
}
//插入头节点
public function addHead($data){
if($this->size == 0){
$this->head = new Node($data);
}else{
$this->head = new Node($data, $this->head);
}
$this->size++;
return true;
}
//插入尾节点
public function addTail($data){
$this->addIndex($this->size, $data);
}
//插入中间节点
public function addIndex($index, $data){
if($index > $this->size || $index < 0)
throw new \Exception('超出链表范围');
if($this->size == 0){
$this->head = new Node($data);
}else{
$cur = $this->getIndexNode($index);
$cur->next = new Node($data, $cur->next);
}
$this->size++;
return true;
}
//获取指定位置的节点
public function getIndexNode($index){
$cur = $this->head;
for($i=0; $i<$index-1; $i++){
$cur = $cur->next;
}
return $cur;
}
//删除头节点
public function delHead(){
if($this->size != 0){
$this->head = $this->head->next;
$this->size--;
return true;
}
return false;
}
//删除尾节点
public function delTail(){
$this->delIndex($this->size-1);
}
//删除中间节点
public function delIndex($index){
if($index > $this->size || $index < 0)
throw new \Exception('超出链表范围');
$cur = $this->getIndexNode($index);
if($this->size != 0){
if($index == 0){
$this->head = $this->head->next;
}else{
$cur->next = $cur->next->next ? $cur->next->next : null;
}
$this->size--;
return true;
}
return false;
}
//转为字符串
public function toString(){
$cur = $this->head;
$str = [];
while($cur != null){
$str[] = $cur->data;
$cur = $cur->next;
}
return implode('->', $str);
}
//反转链表
public function reverse(){
if($this->size != 0) {
$cur = $this->head;
$reveredList = null;
while ($cur != null) {
$next = $cur->next;
$cur->next = $reveredList;
$reveredList = $cur;
$cur = $next;
}
$this->head = $reveredList;
return true;
}
return false;
}
}
#测试
echo '<pre>';
$node = new LinkedList();
$node->addTail(2);
$node->addTail(5);
$node->addTail(3);
$node->addIndex(2, 11);
$node->addHead(33);
$node->delTail();
$node->delIndex(2);
$node->reverse();
print_r($node);