Saturday, August 18, 2012

Push elements into stack. Pop should return the minimum element in the stack.


#include<iostream>

using namespace std;

class stack{
private:
int top;
int a[100];
public:
stack();
void push(int elem);
int pop();
void pushbubble(int elem);
bool isempty();
};

stack::stack(){
this->top = -1;
}

void stack::push(int elem){
a[++(this->top)] = elem;
}

void stack::pushbubble(int elem){
int temp;
if(!this->isempty()){
temp = this->pop();
if(temp > elem){
this->push(temp);
this->push(elem);
} else {
this->pushbubble(elem);
this->push(temp);
}
} else {
this->push(elem);
}
}

bool stack::isempty(){
return (this->top == -1);
}

int stack::pop(){
return a[(this->top)--];
}

int main(){
int a[] = {1,10,2,9,3,8,4,7,5,6};
stack s;
int i;
for(i=0;i<10;i++){
s.pushbubble(a[i]);
}
while(!s.isempty()){
cout<<s.pop()<<endl;
}
return 0;
}

No comments:

Post a Comment