<?php
class Node{
public $data;
public $next;
public function __construct($data=null,$next=null){
$this->data=$data;
$this->next=$next;
}
}
class linkList{
public $head;//头节点,默认一个虚拟节点
public $size;
public function __construct()
{
$this->head=new Node();
$this->size=0;
}
public function add($data){
$current=$this->head;
while ($current->next!==null){
$current=$current->next;
}
$current->next=new Node($data);
$this->size++;
return $this;
}
public function addFirst($data){
$this->head->next=new Node($data,$this->head->next);
$this->size++;
return $this;
}
public function reverselist(){
if ($this->size == 0){
return false;
}
$cur=$this->head->next;
$pre=null;
while ($cur!==null){
$temp=$cur->next;//临时变量 记录操作到哪一个节点
$cur->next=$pre;// 将当前节点的next指向上一个元素(如果是第一个指向NULL)
$pre=$cur; // 保存当前节点信息, 为下一个元素指向使用
$cur=$temp; //当前元素往下移动
}
$this->head->next=$pre;
}
}
$test=new linkList();
$test->add(3);
$test->add(4);
$test->addFirst(2);
var_dump($test);
$test->reverselist();
var_dump($test);
object(linkList)#1 (2) {
["head"]=>
object(Node)#2 (2) {
["data"]=>
NULL
["next"]=>
object(Node)#5 (2) {
["data"]=>
int(2)
["next"]=>
object(Node)#3 (2) {
["data"]=>
int(3)
["next"]=>
object(Node)#4 (2) {
["data"]=>
int(4)
["next"]=>
NULL
}
}
}
}
["size"]=>
int(3)
}
object(linkList)#1 (2) {
["head"]=>
object(Node)#2 (2) {
["data"]=>
NULL
["next"]=>
object(Node)#4 (2) {
["data"]=>
int(4)
["next"]=>
object(Node)#3 (2) {
["data"]=>
int(3)
["next"]=>
object(Node)#5 (2) {
["data"]=>
int(2)
["next"]=>
NULL
}
}
}
}
["size"]=>
int(3)}