MinStack类不提供输出

时间:2017-07-29 10:59:32

标签: c++ visual-c++

MinStack的动态初始化无法做到。为什么呢?

#include<bits/stdc++.h>
#include<iostream>
#include<stdlib.h>
using namespace std;
class Stack
{
    int top;
    int length;
    int *arr;
public:
       //Maximum size of Stack

    Stack(int len)
    {
        top = -1;
        length=len;
        arr=new int[length];
    } //constructor

    void push(int data);
    int pop();
    bool isEmpty();
    bool isStackFull();
    int Size();
    void Display();
    int getPeek();

};

void Stack::push(int data)
{
    if (isStackFull())
    {
        cout << "Stack Overflow"<<endl;
    }
    else
    {
        arr[++top] = data;
    }
}

int Stack::pop()
{
    if (isEmpty())
    {
        cout << "Stack Underflow"<<endl;
        return 0;
    }
    else
    {
        int data = arr[top--];
        return data;
    }
}

bool Stack::isEmpty()
{
    return (top < 0);
}

bool Stack::isStackFull()
{
    return (top == length-1);
}

int Stack::Size()
{
    return (top +1);
}

int Stack::getPeek()
{
    return arr[top];
}

void Stack::Display()
{
    for(int i=top;i!=-1;i--)
    {
        cout<<arr[i]<<" ";
    }
    cout<<endl;
}


class SpecialStack: public Stack
{

public:
    Stack min1;
    SpecialStack(int len):Stack(len)
    {
        min1= new Stack(len);
    }
    int pop();
    void push(int x);
    int getMin();
};
void SpecialStack::push(int x)
{
    if(isEmpty()==true)
    {
        Stack::push(x);
        min1.push(x);
    }
    else
    {
        Stack::push(x);
        int y = min1.pop();
        min1.push(y);
        if( x < y )
        min1.push(x);
        else
        min1.push(y);
    }
}

/* SpecialStack's member method to remove an element from it. This method
removes top element from min stack also. */
int SpecialStack::pop()
{
    int x = Stack::pop();
    min1.pop();
    return x;
}

int SpecialStack::getMin()
{
    int x = min1.pop();
    min1.push(x);
    return x;
}

int main()
{
    SpecialStack s(3); //size of stack should be 3
    s.push(10);
    s.push(20);
    s.push(30);
    cout<<s.getMin()<<endl;
    s.push(5);
    cout<<s.getMin();
    return 0;
}

MinStack的动态初始化无法做到。为什么,如何纠正这个问题。请解释一下。

1 个答案:

答案 0 :(得分:0)

SpecialStack构造函数中,您可以正确初始化基础Stack,但不能初始化min1成员。他们应该以同样的方式处理:

SpecialStack(int len):Stack(len),min1(len)
{ }

如果构造函数初始化列表中没有min1,编译器会尝试调用其默认构造函数,但Stack类没有。{1}}类。