关于php中栈的基本操作

关于php中栈的基本操作

本人算法小白,前几天做过链表的递归翻转之后,对算法产生兴趣,今天在纠结了一个小时的栈的算法终于搞定了,由于网上php相关的栈的基本操作很少,现贴出来给大家参考,大神绕路,不喜勿喷谢谢。

<?php
/**
 * Created by PhpStorm.
 * User: user
 * Date: 07/03/2017
 * Time: 21:35
 */

class node{
    private $value;
    private $pre;
    public function __construct($value){
        $this->value = $value;
        $this->pre = null;
    }
    public function addPre($node){
        $this->pre = $node;
    }
    public function getPre(){
        return $this->pre;
    }
    public function getValue(){
        return $this->value;
    }
}

class stack{
    private $top;
    static public $size;
    public function __construct($value){
        $this->top = new node($value);
    }

    public function push($value){
        $current = $this->top;
        $newNode = new node($value);
        $newNode->addPre($current);
        $this->top = $newNode;
    }

    public function getAllStack(){
        $stack = null;
        $current = $this->top;
        while ($current->getPre() != null){
            $stack .= $current->getValue()."\n";
            $current = $current->getPre();
        }
        return $stack;
    }

    public function getSize(){
        $current = $this->top;
        while (null != $current->getValue()){
            self::$size++;
            $current = $current->getPre();
        }
        return self::$size;
    }

    public function pop(){
        $current = $this->top;
        $this->top = $current->getPre();
        unset($current);
    }

    public function getTop(){
        return $this->top->getValue();
    }
}

$stack = new stack(0);
$stack->push(1);
$stack->push(2);
$stack->push(3);
$stack->push(4);
$stack->push(5);
$stack->push(6);
$stack->push('a');
$stack->push('b');
$stack->push('c');
$stack->push('d');
echo "无出栈顺序:".$stack->getAllStack()."<br>";
$stack->pop();
$stack->pop();
$stack->pop();
echo "三次出栈后:".$stack->getAllStack()."<br>";
echo "此时的栈顶元素:".$stack->getTop()."<br>";
echo "栈的长度为:".$stack->getSize()."<br>";
?>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值