php实现单链表
单链表是最简单的链表表示。用它来表示线性表时,每一个数据元素占用一个结点(node)。一个 结点一般由两个域组成,一个域存放数据元素data; 另一个域存放一个指向链表中下一个结点的指针link,它指出下一个结点 的开始存储地址。而最后一个结点的指针为空。单链表中数据元素之间的逻 辑关系是由结点中的指针指示的,换句话说,指针为数据元素之间的逻辑关系的映象,则逻辑上相邻的两个元素其存储的物理位置不要求紧邻,因此, 这种存储结构为非顺序映像或链式映像。
php使用class模仿单链表实现:
<?php
/**
* @param PHP链表
*/
/**
* 节点类
*/
class Node {
private $Data; //节点数据
private $Next; //下一节点
public function setData($value) {
$this->Data = $value;
}
public function setNext($value) {
$this->Next = $value;
}
public function getData() {
return $this->Data;
}
public function getNext() {
return $this->Next;
}
public function __construct($data, $next) {
$this->setData($data);
$this->setNext($next);
}
}
/**
* 功能类
*/
class LinkList {
private $header; //头节点
private $size; //长度
public function getSize() {
return $this->size;
}
public function getHeader() {
return $this->header;
}
public function __construct() {
header("content-type:text/html; charset=utf-8");
$this->header = new Node(null, null);
$this->size = 0;
}
//param $data--要添加节点的数据
public function add($data) {
$node = $this->header;
while ($node->getNext() != null) {
$node = $node->getNext();
}
$node->setNext(new Node($data, null));
$this->size +=1;
}
//param $data--要移除节点的数据
public function removeAt($data) {
$node = $this->header;
while ($node->getData() != $data) {
$node = $node->getNext();
}
if ($node->getData() != $data) {
print("查无此节点!");
return;
}
$node->setNext($node->getNext());
$node->setData($node->getNext()->getData());
$this->size -=1;
}
//param 遍历
public function get() {
$node = $this->header;
if ($node->getNext() == null) {
print("数据集为空!");
return;
}
while ($node->getNext() != null) {
print($node->getNext()->getData());
if ($node->getNext()->getNext() == null) {
break;
}
$node = $node->getNext();
print '=>';
}
}
/**
* @author MzXy
* @param $data--要访问的节点的数据
* @param 此方法只是演示不具有实际意义
*/
public function getAt($data) {
$node = $this->header->getNext();
if ($node->getNext() == null) {
print("数据集为空!");
return;
}
while ($node->getData() != $data) {
if ($node->getNext() == null) {
break;
}
$node = $node->getNext();
}
if ($node->getData() != $data) {
print("查无此数据!");
return;
}
return $node->getData();
}
/**
* @author MzXy
* @param $value--需要更新的节点的原数据 --$initial---更新后的数据
*/
public function update($initial, $value) {
$node = $this->header->getNext();
if ($node->getNext() == null) {
print("数据集为空!");
return;
}
while ($node->getData() != $value) {
if ($node->getNext() == null) {
break;
}
$node = $node->getNext();
}
if ($node->getData() != $value) {
print("查无此数据!");
return;
}
$node->setData($initial);
}
}
$s = new LinkList();
$s->add('ssss');
echo $s->getSize();
$s->add('fff');
$s->update('ddd', 'ssssd');
echo $s->getSize();
echo $s->get();
?>

浙公网安备 33010602011771号