前几天更新了一篇《php实现基本数据结构之链表》居然还有人看,今天来更新一篇栈与队列的文章。
栈与队列也是链表结构的一种,只不过有些特殊。
栈是一种LIFO(last in first out后进先出)结构, 队列是一种FIFO(first in first out先进先出)结构, 给出两张图体会一下区别。
-
栈模型
-
队列模型
array_push()//将一个或多个单元压入数组的末尾(入栈)
array_unshift()//在数组开头插入一个或多个单元
array_pop()//将数组最后一个单元弹出(出栈)
array_shift()//将数组开头的单元移出数组
复制代码
根据自己的理解给出链式存储栈、队列结构(如果理解的不准确请见谅)
还是先给出Node节点
class Node
{
private $Data;//节点数据
private $Next;//存储下个点对象
public function __construct($data, $next)
{
$this->Data = $data;
$this->Next = $next;
}
public function __set($name, $value)
{
if (isset($this->$name))
$this->$name = $value;
}
public function __get($name)
{
if (isset($this->$name))
return $this->$name;
else
return NULL;
}
}
复制代码
php实现栈结构(粗略实现)
class Stack
{
private $top = NULL;//头节点
/**
* 栈是否为空
* @return bool
*/
public function isEmpty()
{
if ($this->top === NULL)
return TRUE;
return FALSE;
}
/**
* 入栈
* @param $data
*/
public function push($data)
{
$this->top = new Node($data, $this->isEmpty() ? NULL : $this->top);
}
/**
* 出栈 返回出栈的Data
* @return null | data
*/
public function pop()
{
if ($this->isEmpty())
return NULL;
$node = $this->top->Next;
$data = $this->top->Data;
$this->top = $node;
return $data;
}
}
复制代码
php实现队列结构(粗略实现)
class Queue
{
private $front = NULL;//队头
private $rear = NULL;//队尾
public function isEmpty()
{
if ($this->front === NULL || $this->rear === NULL)
return TRUE;
return FALSE;
}
/**
* 入队
* @param $data
*/
public function enQueue($data)
{
if ($this->isEmpty())
$this->front = $this->rear = new Node($data, NULL);
$this->rear->Next = new Node($data, NULL);
}
/**
* 出队
* @return null
*/
public function deQueue()
{
if ($this->isEmpty())
return NULL;
$node = $this->front->Next;
$data = $this->front->Data;
if ($this->front == $this->rear)//当队头跟队尾相同时
$this->rear = $node;
$this->front = $node;
return $data;
}
}
复制代码
以上简写了大致实现栈、队列的链式结构
不得不提的是 革命尚未成功码农仍需努力