PHP 实现一个双端链表

链表中的元素可存储在内存的任何地方。链表的每个元素都存储了下一个元素的地址,从而使一系列随机的内存地址串在一起。

链表存在的问题。在需要读取链表的最后一个元素时,你不能直接读取,因为你不知道 它所处的地址,必须先访问元素#1,从中获取元素#2的地址,再访问元素#2并从中获取元素#3 的地址,以此类推,直到访问最后一个元素。你需要跳跃,链表的效率 真的很低。

使用链表时,插入元素很简单,只需修改 它前面的那个元素指向的地址。而使用数组时,则必须将后面的元素都向后移。

如果你要删除元素呢?链表也是更好的选择,因为只需修改前一个元素指向的地址即可。而 使用数组时,删除元素后,必须将后面的元素都向前移。

数组和链表哪个用得更多呢?显然要看情况。但数组用得很多,因为它支持随机访问。有两 种访问方式:随机访问和顺序访问。顺序访问意味着从第一个元素开始逐个地读取元素。链表只 能顺序访问:要读取链表的第十个元素,得先读取前九个元素,并沿链接找到第十个元素。随机 访问意味着可直接跳到第十个元素。经常说数组的读取速度更快,这是因为它们支持随机访 问。很多情况都要求能够随机访问,因此数组用得很多。数组和链表还被用来实现其他数据结构。

下面用php实现一个双端链表DoubleLinkList.php

<?php
include "Node.php";

class DoubleLinkList
{
	private  $first;    //对链表中第一个链结点的引用
	private  $ends;    //对链表中第一个链结点的引用

	
	public function __construct(){
		$this->first=null;
		$this->ends=null;
	}
	
	 
	public function isEmpty(){
		return ($this->first==null);
	}
	
	/**
	*头部插入
	*/
	public function insertFirst($data){

		$Node=new Node($data);
		if($this->isEmpty()){
			 $this->ends=$Node;
		}else{
			 $this->first->previous=$Node;
			 $Node->next=$this->first;
		}
		$this->first=$Node;
	}
	
    /**
	*
	*尾部插入
	*/
	public function insertLast($data){
		$Node=new Node($data);
		if($this->isEmpty()){
			 $this->first=$Node;
		}else{
			$this->ends->next=$Node;
			$Node->previous=$this->ends;
		}
		$this->ends=$Node;
	}
	
	/**
	*
	*删除节点
	*/
	public function delete($data){
		
		   $current=$this->first;
		   while($current!=null && $current->data!=$data){
			  $current=$current->next;
		   }
		   if($current->previous==null){//删除头部 
			  $this->first= $current->next;
			  $current->next->previous=null;
		   }else{
			  $current->previous->next=$current->next;
		   }
	}
	

	/**
	*
	*遍历
	*/
	public function display(){
		
		$current=$this->first;
		while($current!=null){
			  $current->display();
              $current=$current->next;
		}
	}

}

$DoubleLinkList=new DoubleLinkList();
$DoubleLinkList->insertLast("A");
$DoubleLinkList->insertFirst("B");
$DoubleLinkList->insertLast("D");
$DoubleLinkList->display();
echo "<br/>";
$DoubleLinkList->delete("B");
$DoubleLinkList->display();
?>

Node.php

<?php
class Node
{
	public  $data;
	public  $next;
	public  $previous;
	
	public function __construct($data){
		$this->data=$data;
	}
	
	public function display(){
		echo $this->data;
	}

}
?>



猜你喜欢

转载自blog.csdn.net/rorntuck7/article/details/80897551