双向链表的PHP实现

算法 admin 327℃ 0评论

定义:

双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。

双向链表的PHP实现

<?php
set_time_limit(0);
/**
 * 双向链表不重复,有顺序
 */
class fish{
	private $no;
	private $name;
	private $next = null;
	private $pre = null;

	public function __construct($no = '', $name = ''){
		$this->no = $no;
		$this->name = $name;
	}

	static public function add($head, $fish){
		if($head->next == null){
			$head->next = $fish;
			$fish->pre = $head;
		} else {
			$cur = $head;
			$exists = false;
			while($cur->next != null){
				if($cur->next->no == $fish->no){
					$exists = true;
					die('exists!');
				} elseif($cur->next->no > $fish->no){
					$cur->next = $fish;
					$fish->pre = $cur;
					break;
				} 				
				//后移查找
				$cur = $cur->next;
			}

			if(!$exists){
				$cur->next = $fish;
				$fish->pre = $cur;
			}
		}
	}

	static public function del($head, $no){
		$cur = $head;
		$found = false;
		if($head->next != null){
			while($cur->next != null){
				if($cur->no == $no){
					$found = true;
					$cur->pre->next = $cur->next;
					$cur->next->pre = $cur->pre;
					break;
				} else {
					//后移查找
					$cur = $cur->next;
				}
			}

			if($cur->no == $no){
				$found = true;
				$cur->pre->next = $cur->next;
			}
		} 

		
		if(!$found){
			die('no find');
		}
	}

	static public function show($head){
		$cur = $head;
		while($cur->next != null){
			echo $cur->next->no . ':' . $cur->next->name . '<br>';
			$cur = $cur->next;
		}
		echo '<hr>';
	}
}

$head = new fish();
$f1 = new fish(1, 'fish1');
$f4 = new fish(4, 'fish4');
$f2 = new fish(2, 'fish2');
$f3 = new fish(3, 'fish3');

#fish::show($head);


fish::add($head, $f1);
fish::add($head, $f2);
fish::add($head, $f3);
fish::add($head, $f4);


fish::show($head);

fish::del($head, 4);

fish::show($head);

 

转载请注明:朋克网 » 双向链表的PHP实现

喜欢 (1)
发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址