<?php
class Node {
public $data;
public $next;
public function __construct($data=null, $next=null){
$this->data = $data;
$this->next = $next;
}
}
class Link {
public $head=null;
public $size=0;
public function __construct(){
//$this->head = new Node();
}
//遍历
public function traverse(){
//当前指针位置移动到头部
$curIndex = $this->head;
$tmp = [];
//移动指针一直到没有数据位置
while( !is_null($curIndex) ){
array_push($tmp, $curIndex->data);
//移动指针到当前的下一个节点
$curIndex = $curIndex->next;
}
return $tmp;
}
//头插
public function addAtHead($data){
$node = new Node($data, $this->head);
$this->head = $node;
$this->size++;
return $this;
}
//尾插
public function addAtTail($data){
$node = new Node($data);
$curIndex = $this->head;
//判断当前链表是否为空
if( is_null($curIndex) ){
$this->head = $node;
}
else{
//如果链表不为空,则进行遍历
while( !is_null($curIndex->next) ){
$curIndex = $curIndex->next;
}
$curIndex->next = $node;
}
$this->size++;
return $this;
}
public function addAtIndex($data, $index){
//判断index是头尾的情况
$count = $this->size;
if( $index <= 0 ){
$this->addAtHead($data);
}
if( $index > $count ){
$this->addAtTail($data);
}
//将指针移动到index-1的位置
$curIndex = $this->head;
for($i=0;$i<$index-1;$i++){
$curIndex = $curIndex->next;
}
//新建一个节点,其next是index之后的链表
$node = new Node($data, $curIndex->next);
$curIndex->next = $node;
$this->size++;
return $this;
}
public function delAtIndex($index){
$count = $this->size;
$curIndex = $this->head;
//如果删除的是第一个节点
if( $index == 0 ){
$this->head = $curIndex->next;
$this->size--;
return $this;
}
//如果删除的是最后一个节点
if( $index < 0 || $index > $count ){
echo "没有这个节点\n";
return $this;
}
//将指针移到index-1的位置
for($i=0;$i<$index-1;$i++){
$curIndex = $curIndex->next;
}
//echo "<pre>"; print_r($curIndex);exit;
//此时,curIndex->next所处的位置,也就是index
//将从index开始的链表赋给tmp(tmp所处的位置 = index+2)
$tmp = $curIndex->next;
//index+2后的链表赋值跟index
$curIndex->next = $tmp->next;
$this->size--;
return $this;
}
public function print(){
print_r( $this );
}
}
$link = new Link;
$link->addAtHead(3)
->addAtHead(2)
->addAtHead(1)
->addAtTail(8)
->addAtTail(4)
->addAtTail(5)
->addAtIndex(10, 3)
->delAtIndex(2)
->print();
//$res = $link->traverse();
//$size = $link->size;
//echo "{$size}<pre>"; print_r($res);exit;