Home > php教程 > PHP源码 > php实现双向链表

php实现双向链表

PHP中文网
Release: 2016-05-25 17:07:42
Original
927 people have browsed it

跳至

$n=10;//个数
class link{

	public $val;
	public $next=null;
	public $pre=null;
	static $num=0;
	
	//初始化
	function __construct($num)
	{
		$this->val=$num;
		self::$num++;//别忘记self是一般指向静态变量 静态方法的指针 而this则是初始化后指向对象的指针
	}
	
	//访问结点
	function read_link($val,$head)
	{
		$one=$head->next;
		while($one->valnext;}
		if($one==$head) {echo 'not exist this node!';return;}
		return $one;
	}
	
	//对象个数
	function __get($num)
	{
		return self::$num;
	}
	
	//按照大小增加结点
	function add_link($val,$head)
	{
		$one=$head->next;
		while($one!=$head){
			if($one->valnext;continue;}
			else if($one->val=$val){echo 'linknode is already exist!';return;}
			else if($one->val>$val) break;
		}
		$pre=$one->pre;
		
			$cur=new link($val);
			$pre->next=$cur;
			$one->pre=$cur;
			$cur->next=$one;
			$cur->pre=$pre;
		
		return $cur;
	}
	//删除该结点
	function delete_node($val,$head)
	{
		$one=$head->next;
		while($one!=$head) {
			if($one->val!=$val) {$one=$one->next;continue;}
			else break;
		}
		if($one==$head) {echo 'not exist linknode!';return;}
		else{
			$pre=$one->pre;
			$next=$one->next;
			$pre->next=$next;
			$next->pre=$pre;
			$one=new link(NULL);//引用变量值改变不影响被引用变量的值
			//unset($one);只是引用数减1 并不能删除
		}
		return $one;
	}

	
}
$head=new link(null);
for($i=1;$inext=$cur;
		$cur->pre=$head;
	}else if($i==$n){//最后一次则和头结点在一起
		$cur=new link($i);
		$temp->next=$cur;
		$cur->next=$head;
		$head->pre=$cur;
	}
	else{
		$cur=new link($i);
		$temp->next=$cur;
		$cur->pre=$temp;
	}
	
}

//var_dump($head->read_link(10,$head)->val);访问结点

//var_dump($head->add_link(10,$head));//增加结点
//var_dump($head->add_link(100,$head)->val);

//var_dump($head->delete_node(102,$head));//删除结点	
//var_dump($head->delete_node(10,$head)->val);
//var_dump($head->read_link(10,$head)->val);

/* $a=1;
$b=$a;	
$b=NULL;
echo $a;//看来引用变量改变值的时候 两个变量就独立咯
//unset($b);
$a=NULL;var_dump($b);//看来变量有引用和被引用的关系
echo $a; 
 */
Copy after login

                   

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template