题目2:
设计包含min 函数的栈。
定义栈的数据结构,要求添加一个min 函数,能够得到栈的最小元素。
要求函数min、push 以及pop 的时间复杂度都是O(1)。#include<iostream>
using namespace std;
#define Maxsize 5
typedef struct/*存放数值*/
{
int arr[Maxsize];
int top;
}Mystack;
typedef struct/*存放曾经最小的数值*/
{
int brr[Maxsize];
int top;
}Minstack;
void Push(Mystack*& s,int num)
{
if(s->top > Maxsize-1)
{
printf("stack is full!\n");
exit(0);
}
s->top++;
s->arr[s->top] = num;
}
void Push(Minstack*& t,int num)
{
if(t->top > Maxsize-1)
{
printf("stack is full!\n");
exit(0);
}
t->top++;
t->brr[t->top] = num;
}
int Gettop(Minstack*& temp)
{
if(temp->top!=-1)
{
return temp->brr[temp->top];
}
else
{
cout<<"minstack is empty"<<endl;
return -1;
}
}
int Pop(Minstack *&t)
{
int num;
if(t->top == -1)
{
printf("after pop minstack is empty!\n");
exit(0);
}
num = t->brr[t->top--];
return num;
}
int Pop(Mystack *&s)
{
int num;
if(s->top == -1)
{
printf("after pop stack is empty!\n");
exit(0);
}
num = s->arr[s->top--];
return num;
}
int Min(int temp,Minstack* &t)
{
int top;
int pop;
top= Gettop(t);
if(temp<=top)
{
pop= Pop(t);
}
top=Gettop(t);
return top;
}
int main( )
{
int i,poptmp;
int num,min;
Mystack *s;
Minstack *t;
/*初始化栈*/
s = (Mystack*)malloc(sizeof(Mystack));
s->top = -1;
t = (Minstack*)malloc(sizeof(Minstack));
t->top = -1;
cout<<"请输入5个数值:";
cin>> num;
Push(s,num);
Push(t,num);
for(i = 1;i < Maxsize; i++)
{
cin>> num;
Push(s,num);
poptmp = Gettop(t);
if(num < poptmp)
{
Push(t,num);
}
}
min=Gettop(t);
cout<<"最小数值为: \t"<<min<<endl;
cout<<"poping"<<endl;
while(s->top != -1)
{
poptmp = Pop(s);
cout<<"myStack pop :"<<poptmp<<endl;
min=Min(poptmp,t);
if(min==-1)
{
cout<<" myStack is empty"<<endl;
}
else
{
cout<<"最小数值为: \t"<<min<<endl;
}
}
return 0;
}
得到结果如下:
*************************************
请输入5个数值:5
4
3
6
2
最小数值为: 2
poping
myStack pop :2
最小数值为: 3
myStack pop :6
最小数值为: 3
myStack pop :3
最小数值为: 4
myStack pop :4
最小数值为: 5
myStack pop :5
minstack is empty
myStack is empty*****************************************
附上JULY提供的思路:
首先我做插入以下数字:10,7,3,3,8,5,2, 6
0: 10 -> NULL (MIN=10, POS=0)
1: 7 -> [0] (MIN=7, POS=1) 用数组表示堆栈,第0个元素表示栈底
2: 3 -> [1] (MIN=3, POS=2)
3: 3 -> [2] (MIN=3, POS=3)
4: 8 -> NULL (MIN=3, POS=3) 技巧在这里,因为8比当前的MIN 大,所以弹出8不会对当前
的MIN 产生影响
5:5 -> NULL (MIN=3, POS=3)
6: 2 -> [2] (MIN=2, POS=6) 如果2出栈了,那么3就是MIN
7: 6 -> [6]
辅助栈B 中,始终保存着最小的元素。当pop A 中的元素小于B 中栈顶元素时,则也要pop B 中栈顶元素
*******************************************************************************************************************************
抛出做题的一个小困惑:
int Gettop(Minstack*& temp)const//编译出错;
{
if(temp->top!=-1)
{
return temp->brr[temp->top];
}
else
{
cout<<"minstack is empty"<<endl;
return -1;
}
}这个函数const int func(const int& a) const声明中,三个const
第一个:const修饰普通变量没有意思,在引用,指针时,只能用对应的const常量接受返回值;第二个:不会复制函数,可以提高编程效率,但是实参必须是常量;
第三个:在函数中不能改变变量值; const限制不能修改this指向的对象的取值,也就是不能修改自身的状态。
我的Gettop()怎么通不过???-?!!!