php实现简单的单链表

<?php
/**
 * 建立一个链表,节点的data为数组,记录一个id,完成链表所以操作
 */

//结点,结点数据data定义为一个数组,id和value
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(){
		$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){
			//print_r($current->next->data);
			//echo "<br/>";
			echo $current->next->data['value'];
			$current = $current->next;
		}
	}
	
	//获取链表长度,不含头结点(空)
	public function getLength(){
		$len = 0;
		$current = $this->header;
		while ($current->next !== null) {
			$len++;
			$current = $current->next;
		}
		return $len;
	}
	
	//查找value是否在list中,存在返回id,否则false
	public function find($value){
		$current = $this->header;
		$flag = 0;
		while ($current->next!==null){
			if($value == $current->next->data['value']){
				$flag = 1;
				$id = $current->next->data['id'];
				break;
			}
			$current = $current->next;
		}
		if($flag == 0){
			return false;
		}else{
			return $id;
		}
	}
	
	//插入一个结点,在id之前
	public function insert(Node $node,$id){
		$current = $this->header;
		while ($current->next!==null){
			if($id == $current->next->data['id']){
				$tmp = $current->next;
				$current->next = $node;
				$current->next->next = $tmp;
				break;
			}
			$current = $current->next;
		}
	}
	
	//删除一个结点(第一个出现的)
	public function del($id){
		$current = $this->header;
		while ($current->next!=null){
			if($current->next->data['id'] == $id){
				$current->next = $current->next->next;
				break;
			}
			$current = $current->next;
		}
	}
	
	//更新结点value
	public function update($id,$value){
		$current = $this->header;
		while ($current->next !==null){
			if($current->next->data['id'] == $id){
				$current->next->data['value'] = $value;
			}
			$current = $current->next;
		}
	}
}

class Client{
	public static function main(){
		$list = new LinkList();
		$data1 = array(
			'id'=>1,
		    'value'=>'hello ',
		);
		$data2 = array(
			'id'=>2,
			'value'=>'world',
		);
		$data3 = array(
			'id'=>3,
			'value'=>'!',
		);
		
		$node1 = new Node($data1);
		$node2 = new Node($data2);
		$node3 = new Node($data3);

		$list->add($node1);
		$list->add($node2);
		$list->add($node3);
		
//		$list->show();
//		echo "<br/>";
		
		$node4 = new Node($data3);
		$list->insert($node4, 2);
		//$list->del(3);
		$list->update(3, '!!!');
		$list->show();
		echo "<br/>";
		
	}
}

Client::main();
?>

  增加结点、删除结点、查找结点、修改结点、获取长度,遍历均实现。

posted @ 2014-11-13 11:29  tai君  阅读(285)  评论(0编辑  收藏  举报