php 单链表构造 反转

<?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)

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值