博客
关于我
栈和队列算法
阅读量:774 次
发布时间:2019-03-24

本文共 2540 字,大约阅读时间需要 8 分钟。

PHP堆栈实现
1、实现一个MinStack
                            #pragma once                <?php                #define MAX_VALUE 100                typedef struct MinStack {                    int array[MAX_VALUE];                    int top;                } MinStack;                void Init(MinStack *pMs) {                    pMs->top = 0;                }                void Push(MinStack *pMs, int data) {                    int min = data;                    if (pMs->top != 0 && pMs->array[pMs->top - 1] < min) {                        min = pMs->array[pMs->top - 1];                    }                    pMs->array[pMs->top++] = data;                    pMs->array[pMs->top++] = min;                }                void Pop(MinStack *pMs) {                    pMs->top -= 2;                }                int Min(MinStack *pMs) {                    return pMs->array[pMs->top - 1];                }                int Top(MinStack *pMs) {                    return pMs->array[pMs->top - 2];                }                void test1() {                    MinStack ms;                    Init(&ms);                    $arr = array(3, 2, 5, 6, 8, 3, 1, 9);                    foreach ($arr as $i => $val) {                        Push(&ms, $val);                    }                    echo Min(&ms) . " ";                    Pop(&ms);                    echo Min(&ms) . " ";                    Pop(&ms);                    echo Min(&ms) . " ";                }                    
2、改进方法
方法1:使用一个栈实现交叉存放数据
方法2:使用两个栈实现更高效的操作
3、其他技术问题
使用两个栈实现队列
            <?php            class Solution {                private Stack stack1;                private Stack stack2;                public void push(int node) {                    stack1.push($node);                }                public int pop() {                    if (stack2.isEmpty()) {                        while (!stack1.isEmpty()) {                            stack2.push(stack1.pop());                        }                    }                    return stack2.pop();                }            }            </?php        
4、字符串数组运算示例
            $str = array("2", "4", "+", "9", "*");            $result = Solution::evalRPN($str);            var_dump($result);        

转载地址:http://udlkk.baihongyu.com/

你可能感兴趣的文章
python | gunicorn,一个非常实用的 Python 库!
查看>>
python | h5py,一个无敌的关于 HDF5 的 Python 库!
查看>>
python | huey,一个非常厉害的 任务调度 Python 库!
查看>>
python | hypothesis,一个有趣的 Python 库!
查看>>
python | Indico,一个超酷的 Python 库!
查看>>
python | isort,一个有趣的 自动整理导入语句 的Python 库!
查看>>
python | jinja,一个超酷的 Python 库!
查看>>
python | joblib,一个强大的 Python 库!
查看>>
python调用git bash_Python学习第70课-用Git Bash在命令行打开sublime
查看>>
python | jsonschema,一个实用的 验证 JSON 数据结构 Python 库!
查看>>
python课程的中期报告范文_课题研究中期总结报告范文
查看>>
python | lxml,一个超酷的 关于XML/HTML 文档 Python 库!
查看>>
python | mplfinance,一个有趣的金融数据可视化 Python 库!
查看>>
python | nipy,一个强大的关于 神经影像数据分析 的Python 库!
查看>>