php实现基本数据结构之栈、队列

前几天更新了一篇《php实现基本数据结构之链表》居然还有人看,今天来更新一篇栈与队列的文章。

栈与队列也是链表结构的一种,只不过有些特殊。

栈是一种LIFO(last in first out后进先出)结构, 队列是一种FIFO(first in first out先进先出)结构, 给出两张图体会一下区别。

  • 栈模型

  • 队列模型

    看到网上的一些帖子用PHP内置函数来实现栈、队列顺序存储结构

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;
    }

}
复制代码

以上简写了大致实现栈、队列的链式结构

不得不提的是 革命尚未成功码农仍需努力

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值