php实现简单的单链表

<?php 
//节点类,数据和指向下一节点指针
class Node{
	public $data;
	public $next;
	
	public function __construct($data,$next=null){
		$this->data = $data;
		$this->next = $next;
	}
}

//链表类
class LinkList{
	public $header;
	
    public function __construct(Node $node){//头节点不为空
    	$this->header = $node;
    }
    
    public function add(Node $node){
    	$current = $this->header;
    	while ($current->next!==null){
    		$current = $current->next;
    	}
    	$current->next = $node;
    }
    
    public function show(){
    	$current = $this->header;
    	while ($current->next !== null){
    		echo $current->data;
    		echo "<br/>";
    		$current = $current->next;
    	}
    	echo $current->data;
    }
    
    
}
//头结点为空的链表
class LinkListOne{
	public $header;
	
	public function __construct(){
		$this->header = new Node(null);
	}
	
	public function add(Node $node){
		$current = $this->header;
		while($current->next!==null){
			$current = $current->next;
		}
		$current->next = $node;
	}
	
	public function show(){
		$current = $this->header;
		while($current->next!==null){
			echo $current->next->data;
			echo "<br/>";
			$current = $current->next;
		}
	}
}
class Client{
	public static function main(){
		$node1 = new Node(1);
		$node2 = new Node(2);
		$node3 = new Node(3);
		$node4 = new Node(4);
		$linklist = new LinkListOne();
		$linklist->add($node1);
		$linklist->add($node3);
		$linklist->add($node4);

		$linklist->show();
	}
}
Client::main();

?>

  

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。