这个是php链表的实现。php内存栈中一个对象名对应的是一个地址,改地址对应的是真实内容,所以可用next变量存储下一个节点对象的地址,以实现链表。
在链表类还可以加入一个记录链表长度的变量(优化),这样可以方便一些操作。
//设计链表
//定义节点类
error_reporting(E_ERROR);
class Node{
public $val;
public $next;
function __construct($val = 0){
$this->next = null;
$this->val = $val;
}
}
//定义链表类
class MyLinkedList{
public $head;
function __construct(){
$this->head = new Node();//给头结点赋初值(可注释掉该初始化节点)
}
//获取第index个节点的值
public function get($index){
if($index < 0){
return -1;
}
$start = $this->head;
for($i = 0;$i < $index;$i++){
$start = $start->next;
}
if(is_null($start)){
return -1;
}
return $start->val;
}
//往链表头节点方向加入一个节点
public function addAtHead($val){
$this->addAtIndex(0,$val);
}
//往链表尾部加入一个节点
public function addAtTail($val){
$node = new Node($val);
$start = $this->head;
for($i = 1;;$i++){
$pre = $start;//存取上一个节点
$start = $start->next;
if(is_null($start)){
$pre->next = $node;
break;
}
}
}
//往链表index节点前添加一个节点为$val
public function addAtIndex($index,$val){
$node = new Node($val);
if($index <= 0){
$node->next = $this->head;
$this->head = $node;
}else{
$start = $this->head;
$type = null;
for($i = 0;;$i++){
$pre = $start;
$start = $start->next;
if($type){//如果index大于链表的长度
$type->next = null;
return -1;
}
if(is_null($pre)){//如果index等于链表的长度
$pre->next = $node;
$type = $pre;
continue;
}
if($i+1 == $index){
$node->next = $start;
$pre->next = $node;
break;
}
}
}
}
//修改index节点为val值
public function editAtIndex($index,$val){
$start = $this->head;
for($i = 0;;$i++){
$pre = $start;
$start = $start->next;
if($i == $index){
$pre->val = $val;
break;
}
}
}
//删除第index节点
public function deleteAtIndex($index){
if($index < 0){
return -1;
}
$start = $this->head;
if($index == 0){
$this->head = $start->next;
}else{
for($i = 0;;$i++){
$pre = $start;
$start = $start->next;
if(is_null($start)){
return -1;
}
if($i+1 == $index){
$pre->next = $start->next;
}
}
}
}
//打印当前链表
public function printList(){
$start = $this->head;
for($i = 0;;$i++){
echo $i.':';
echo $start->val.PHP_EOL;
$start = $start->next;
if(is_null($start)){
break;//查询链表结束
}
}
}
}
$linkedList = new MyLinkedList();
$linkedList->addAtHead(1);
$linkedList->editAtIndex(0,3);
$linkedList->printList();
$linkedList->addAtTail(3);
$linkedList->addAtIndex(1,2);
$linkedList->get(1);
$linkedList->deleteAtIndex(1);
var_dump($linkedList->get(1));