Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
C:
#include<stdlib.h>
#include<stdio.h>
struct node
{
int data;
struct node* down;
};
typedef struct node node;
struct stack
{
node* top;
int size;
};
typedef struct stack Stack;
Stack* EmptyStack()
{
Stack *top = (Stack*)malloc(sizeof(Stack*));
if(top)
{
top->top = NULL;
top->size = 0;
}
return top;
}
void push(Stack* stack,Stack* minstack,int x) {
node* newtop=(node *)malloc(sizeof(node));
newtop->data=x;
newtop->down=stack->top;
stack->top=newtop;
stack->size++;
if(minstack->top==NULL || x <= minstack->top->data){
node* newmin=(node *)malloc(sizeof(node));
newmin->data=x;
newmin->down=minstack->top;
minstack->top=newmin;
minstack->size++;
}
return;
}
void pop(Stack* stack,Stack* minstack){
node* p;
int d;
if(stack->top==NULL && stack->size==0) return;
else{
p=stack->top;
d=stack->top->data;
stack->top=stack->top->down;
stack->size--;
free(p);
if(d == minstack->top->data){
if(minstack->top == NULL && minstack->size == 0) return;
else {
p=minstack->top;
minstack->top=minstack->top->down;
stack->size--;
free(p);
}
}
}
return;
}
int top(Stack* stack) {
return stack->top->data;
}
int getMin(Stack* minstack){
return minstack->top->data;
}
void main(){
Stack* stack=EmptyStack();
Stack* minstack=EmptyStack();
int data;
scanf("%d",&data);
while(data>=0) {
push(stack,minstack,data);
scanf("%d",&data);
}
pop(stack,minstack);
printf("%d\n",getMin(minstack));
}C++
class MinStack {
private:
stack<int> datastack;
stack<int> minstack;
public:
void push(int x) {
datastack.push(x);
if(minstack.empty() || x<=minstack.top())
minstack.push(x);
}
void pop() {
int data=datastack.top();
datastack.pop();
if(data==minstack.top()) minstack.pop();
}
int top() {
return datastack.top();
}
int getMin() {
return minstack.top();
}
};
原文:http://blog.csdn.net/uj_mosquito/article/details/41944337