链表的设计与实现(php)

这个是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));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值