类最小堆栈未给出输出

Class MinStack not giving output

本文关键字:输出 堆栈      更新时间:2023-10-16

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的动态初始化是无法做到的。为什么,如何纠正这个问题。请解释一下。

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

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

当构造函数初始值设定项列表中没有min1时,编译器会尝试调用其默认构造函数,但Stack类没有