类最小堆栈未给出输出
Class MinStack not giving output
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
类没有
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 提升::堆栈跟踪::safe_dump_to输出大小
- 如何使用方法覆盖在输出屏幕上显示堆栈整数值
- 自定义堆栈上 std::string 数据的输出
- 如何在 C++ 中将从文本文件中读取的元素推送和弹出到数组中,并按 Revserse 顺序输出堆栈?
- 类最小堆栈未给出输出
- 从堆栈中读取字符后,如何修复不正确的文件输出
- 当程序与符号名称一起崩溃时,输出呼叫堆栈
- C 堆栈实现意外输出
- 在Visual Studio 2013 C++中使用GLUT渲染Kinect输出(堆栈溢出)
- stl数据结构的堆栈上输出参数与返回值的效率
- 程序在特定场景下不输出所需的输出:堆栈和解析
- 为什么这是此异常堆栈的输出
- 如何从opfile输出中获取调用堆栈
- c++程序成功构建,没有输出,只显示堆栈跟踪