zoukankan      html  css  js  c++  java
  • careercup-栈与队列 3.1

    3.1 描述如何只用一个数组来实现三个栈。

    解答

    我们可以很容易地用一个数组来实现一个栈,压栈就往数组里插入值,栈顶指针加1; 出栈就直接将栈顶指针减1;取栈顶值就把栈顶指针指向的单元的值返回; 判断是否为空就直接看栈顶指针是否为-1。

    如果要在一个数组里实现3个栈,可以将该数组分为3个部分。如果我们并不知道哪个栈将装 入更多的数据,就直接将这个数组平均分为3个部分,每个部分维护一个栈顶指针, 根据具体是对哪个栈进行操作,用栈顶指针去加上相应的偏移量即可。

    C++实现代码:

    #include<iostream>
    #include<new>
    using namespace std;
    
    class stack3
    {
    private:
        int top[3];//仅仅用来记录偏移量
        int size;
        int *buf;
    public:
        stack3(int size=300)
        {
            buf=new int[3*size];
            this->size=size;
            top[0]=top[1]=top[2]=-1;
        }
      ~stack3()
      {
        delete []buf;
      }
    void push(int stackNum,int val) { top[stackNum]++; int idx=top[stackNum]+stackNum*size; buf[idx]=val; } void pop(int stackNum) { top[stackNum]--; } int gettop(int stackNum) { int idx=top[stackNum]+stackNum*size; return buf[idx]; } bool empty(int stackNum) { return top[stackNum]==-1; } }; int main() { stack3 mystack;//stack3 mystack; for(int i=0; i<10; ++i) mystack.push(0, i); for(int i=10; i<20; ++i) mystack.push(1, i); for(int i=100; i<110; ++i) mystack.push(2, i); for(int i=0; i<3; ++i) cout<<mystack.gettop(i)<<" "; cout<<endl; for(int i=0; i<3; ++i) { mystack.pop(i); cout<<mystack.gettop(i)<<" "; } mystack.push(0, 111); mystack.push(1, 222); mystack.push(2, 333); for(int i=0; i<3; ++i) cout<<mystack.gettop(i)<<" "; return 0; }
  • 相关阅读:
    org.Hs.eg.db
    Error in readRDS(dest) : error reading from connection
    R语言中的特殊值 NA NULL NaN Inf
    C#转Java之路之三:多线程并发容器即线程安全的容器
    C#转Java之路之二:多线程原子变量
    C#转Java之路之一:线程
    H5 input type="search" 不显示搜索 解决方法
    陪你在路上...我却渐行渐远
    Extjs使用 RestfulWebApi +Token验证小结
    Oracle 10g的备份与还原
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4142137.html
Copyright © 2011-2022 走看看