Lecture 6 Stacks
Lecture 6 Stacks
Lecture 6
STACKS
Stacks
A
E.g.
Operation On Stack
Creating
a stack
Checking stack---- either empty or
full
Insert (PUSH) an element in the
stack
Delete (POP) an element from the
stack
Access the top element
Display the elements of stack
Push
Stack-Related Terms
Top
Underflow
Overflow
Stack Implementation
Implementation
Static implementation
Dynamic Implementation
Static
Implementation
Implementation
Static Implementation
top
First Element
Second Element
List
Last Element
maxlength
Empty
Static Implementation
1
3
2
2
1
1
Static Implementation
Since, in a stack the insertion and
deletion take place only at the top, so
A better Implementation:
Anchor the bottom of the stack at the
bottom of the array
Let the stack grow towards the top of
the array
Top indicates the current position of
the first stack element.
Static Implementation
A better Implementation:
top
1
2
First Element
Second Element
.
.
maxlength
Last Element
Constructor
IntStack::IntStack(int size)
{
stackArray = new int[size];
stackSize = size;
top = -1;
}
Push( )
void IntStack::push()
{
clrscr();
int num;
if(top>=stackSize)
cout<<"stack Overflow"<<endl;
else
{
cout<<"Enter Number=";
cin>>num;
top++;
stackArray[top]=num;
}
}
Pop( )
void IntStack::pop()
{
clrscr();
if(top == -1)
cout<<"Stack Underflow"<<endl;
else
{
cout<<"Number Deleted From the stack=";
cout<<stackArray[top];
top--;
}
getche();
}
Main( )
void main ()
{
IntStack stack(5);
int choice;
do
{
cout<<Menu"<<endl;
cout<<"1-- PUSH"<<endl;
cout<<"2-- POP"<<endl;
cout<<"3 DISPLAY
"<<endl;
cout<<"4-- Exit"<<endl;
cout<<"Enter choice=";
cin>>choice;
switch(choice)
{
case 1:
stack.push(); break;
case 2:
stack.pop(); break;
case 3:
stack.displayStack();
break;
}
}while(choice!=4);
getche();
}
Dynamic Implementation of
Stacks
As
NULL
Dynamic Implementation of
Stack
Class Definition
class ListStack{
private:
struct node{
int num;
node *next;
}*top;
public:
ListStack(){ top=NULL;}
void push();
void pop();
void display();
};
Push( ) Function
This
void ListStack::push()
{
node *newNode;
newNode= new node;
cout<<Enter number to add on stack";
cin>> newNode->num;
newNode->next=top;
top=newNode;
}
Pop( ) Function
void ListStack::pop()
{
node *temp;
temp=top;
if(top==NULL)
cout<<"Stack UnderFlow"<<endl;
else
{
cout<<"deleted Number from the stack =";
cout<<top->num;
top=top->next;
delete temp;
}
}
Main( ) Function
void main()
switch(choice){
case 1:
clrscr();
LS.push();
ListStack LS;
break;
int choice;
case 2:
do{
LS.pop();
cout<<"Menu "<<endl;
break;
cout<<"1.Push" <<endl;
case 3:
LS.display();
cout<<"2.Pop"<<endl;
break;
cout<<"3.Show"<<endl;
cout<<"4.EXIT"<<endl;
cin>>choice;
}while(choice!=4);
}
Stack applications
Back
Undo
Reversing
Saving
When
When
Pointers
new & delete Operators