Professional Documents
Culture Documents
Definition
A Stack is a data structure containing
finite elements of the same type and with
which you can perform the following
operations.
Add data, one item at a time, Push
Access the data item on the top (other
data items are hidden from view), Top
Remove and discard the data item on the
top, thus exposing the next item which
now becomes the top item, Pop.
Definition…
In a stack bottom is fixed and all stack
operations are done at top end.
The order in which data in added,
accessed and removed is LIFO (last in,
first out).
Stacks can be implemented using “arrays”
and “linked lists”.
Linked lists is already studied.
Functions performed by a stack
Push
Insert an item x into top of the stack and returns new
stack S with top pointing to the new item x.
Pop
Delete the item x pointed by the top of the stack and
returns new stack S with top is pointing to the item next
down to the deleted item.
isEmpty
Checks whether the stack is empty or not.
Stack Insertion
Top=-1
•Stack is empty
•Top=NULL or -1
Push(1)
1 Top=0
5 Top=1
5
1
Push(20)
10
5
1
20
Push(40)
10
5
20
Push(80)
10
5
10
5
•Topitem is deleted
Top=3
pop()
10 Top=2
5 Top=1
1 Top=0
Top=NULL or -1
Top=NULL or -1
•Top=-1 or NULL
pop()
Top=NULL or -1
•Top=-1 or NULL
Pseudo code and C++ code (Push)
Procedure 6.1
void push(int MaxStk, int* top1,
Push(Stack,Top,MaxStk,Item) char *STK
,char item)
{
1. [Stack already filled?] if( *top1==MaxStk-1)
If Top=MaxStk-1, then print {
Overflow, and return cout<<"\n\nStack is
Full";
1. Set Top=Top+1. [increase exit(1);
Top by 1] }
else
2. Set Stack[Top]:=Item, {
[Inserts Item in new TOP *top1=*top1+1;
position] STK[*top1]=item;
}
cout<<"\n\ntop = "<<*top1;
3. Return
}
Pseudo code and C++ code (Pop)
Procedure 6.2
void pop(int top1, char *STK )
Pop(Stack, Top, Item) {
if(*top1==-1)
[Stack has an item to be
{
removed?]
cout<<"The stack is empty\n";
if Top=0, then: Print: }
Underflow, and Return.
else
{
2. Set Top=Top-1. [Decreses *top1=*top1-1;
Top by 1.] cout<<"the deleted element is\n”;
cout<<STK[*top1+1];
3. Return }
cout<<"top = "<<*top1;
}
Main Program
void main(void)
{
clrscr();
char *STK;
int MaxStk=0, top=-1;
int* top1;
top1=⊤
cout<<"Enter the max number of items in array: ";
cin>>MaxStk;
STK=new char[MaxStk];
push(MaxStk,top1,STK,'[');
Main Program…
getch();
push(MaxStk,top1,STK,'c');
getch();
push(MaxStk,top1,STK,']');
getch();
pop(top1,STK);
getch();
pop(top1,STK);
getch();
pop(top1,STK);
getch();
}
Stack Implementation in OOP
class Stack { Stack::Stack(){
private: size = 10;
int size, top; top = -1;
int * arr; arr = new int[size];}
????