0% found this document useful (0 votes)
35 views50 pages

4 Stacks

Uploaded by

Aarushi Chopkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views50 pages

4 Stacks

Uploaded by

Aarushi Chopkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

STACKS

Stacks
• Stack is an ordered list of items, ordered in the input sequence.
• Basically, items are inserted and deleted at one end, called the
top of the stack.
• Works on principle last in first out (LIFO).
• Other names used for stacks are piles and pushdown list.
• Adding an item
– Referred to as pushing it onto the stack.
• Removing an item
– Referred to as popping it from the stack.
Last In First Out

top
top E top
D D D
C top C C C
B top B B B B
A top
A A A A A
Empty push(A) push(B) push(C) push(D) push(E) pop(E)
stack
Implementation of Stacks
• Stack can be implemented based on
–Array (static implementation)
–Linked list (dynamic implementation)

Operations perform on stack


 Create the stack
 Push the element on stack
 Pop the element from stack
 Check the stack is empty or full
Array-based Stack Implementation
• The simplest way of representing a stack is by using a one-
dimensional array.

• Structure definition for stack:


struct stack
{
int stk[5];
int top;
}st;
Array-based Stack Implementation
Empty
Stack
Push(10)
4
4 Increament top by 1, as
st.top++; 3
3 2
2 1
1 0 st.top
0
st.top= -1

4
Store data 10, as
3
st.stk[st.top]=10;
2
1
10 0 st.top
Array-based Stack Implementation
Empty
Stack
Push(56)
4
4 Increament top by 1, as
st.top++; 3
3 2
2 1 st.top
1 10 0
0
st.top= -1

4
Store data 56, as
3
st.stk[st.top]=56;
2
56 1 st.top

10 0
Array-based Stack Implementation
Empty
Stack
push(10) push(56) push(80) push(32)

4 4 4 4 4
3 3 3 3 32 3 st.top

2 2 2 80 2 st.top 80 2
1 1 56 1 st.top 56 1 56 1
0 10 0 st.top 10 0 10 0 10 0
st.top= -1

push(96) Push(96) is not possible


push(45)
st.top since stack is full.
45 4
45 4 st.top
32 3
32 3
80 2
80 2
56 1
56 1
10 0
10 0
Array-based Stack Implementation

Pop( ) Pop( ) Pop( ) Pop( ) Pop( )

45 4 st.top 4 4 4 4
32 3 32 3 st.top 3 3 3
80 2 80 2 80 2 st.top 2 2
56 1 56 1 56 1 56 1 st.top 1
10 0 10 0 10 0 10 0 10 0 st.top

Empty
Stack

4
3
2
1
0 st.top= -1
Array-based Stack Implementation continue…..
Algorithm :
1.Define structure containing array for stack and top as
variable for top of stack.
2.Initialize stack top to -1.
3.Perform push operation,
-Before pushing data onto stack ,
check stack is full or not.
-If full, print as stack is full.
-else
Enter the data to be pushed from user.
Increment the counter i.e. top
Insert that data onto stack
Push Operation
printf("\n\tPUSH");

if(st.top==MAX-1)
{
printf("\n\tSTACK IS FULL!");
}
else
{
printf("\n\tENTER THE ELEMENT TO BE PUSHED: ");
scanf("%d",&num);
st.top++;
st.stk[st.top]=num;
}
Push Operation & stack full condition
using function
void push(int num)
{ if(full()==1)
int full()
printf("\n\tSTACK IS FULL!");
{
else
if(st.top==max-1)
{
return 1;
st.top++;
else
st.stk[st.top]=num;
return 0;
}
}
}
Array-based Stack Implementation continue…..

4. Before popping the data from stack , check stack is empty


or not.
If it is empty, print stack is empty.
If not , Print the popped data and
decrement the counter top.
5.Display stack data
check stack is empty or not.
Pop Operation
printf("\n\tPOP");
if(st.top = = -1)
{
printf("\n\tSTACK IS EMPTY!");
}
else
{
num=st.stk[st.top];
st.top--;
printf("\n\tELEMENT POPPED IS: %d",num);
}
Pop Operation & stack empty condition
using function
int pop()
{ if(empty()==1)
printf("\n\tSTACK IS Empty!"); int empty()
else {
{ if(st.top== -1)
int num; return 1;
num=st.stk[st.top] else
st.top--; return 0;
return(num); }
}
}
Display Operation
printf("\n\tDISPLAY");

if(st.top==-1)
{
printf("\n\tSTACK IS ENPTY!");
}
else
{
printf("\n\tTHE STACK IS:");
for(i=st.top; i>=0; i--)
{
printf("\n\t%d",st.stk[i]);
}
}
Display Operation using function
void display()
{
int i;
if(empty()==1)
printf(“\n\t STACK IS EMPTY”);
else
{
printf("\n\tTHE STACK IS:");
for(i=st.top; i>=0; i--)
{
printf("\n\t%d",st.stk[i]);
} //End of for loop
} // End of else
} // End of Display function
Linked list-based Stack Implementation
Algorithm :
1.Define structure containing data to be enter on the stack
and link to the next data.
2.Initialize stack top to NULL.
3.Perform push operation,
a. Create new node as p using malloc.
b. Enter data to be pushed onto the stack.
c. make p->next=NULL;
e. If top==NULL, make top=p;

struct stack
else, p->next=top;
{
top=p; int number;
struct stack *next;
}*top, *p;
Linked list-based Stack Implementation

if top=NULL, Stack is empty.

Push(10)
Create the node using malloc function,

p
100
Enter the data as 10 in number field, as
p->number=10 and make next field as NULL and this is first node
in stack so top must point to p as top=p;

10 NULL
p
100
top
Linked list-based Stack Implementation
Push(30)
Create the node using malloc function,
p
150
Enter the data as 30 in number field, as p->number=30 and make
next field point to top.
p 30
150

top 10 NULL
100
Now top must be point node which is pushed last as top= p;
p 30
top 150

10 NULL
100
Linked list-based Stack Implementation

push(80)

p 80
top 300

30
150

10 NULL
100

To display content of stack traverse from top to NULL.


It will display as:
80
30
10
Linked list-based Stack Implementation

p 80
top 300 Pop():
It will pop top element as p=top;
and top is pointing to node containing value 30 using
30 statement top=top->next;
150 And node get deleted using free(p);

10 NULL
100

top 30
150

10 NULL
100
Push Operation
void push() /*FUNCTION FOR PUSHING ELEMENTS*/
{
printf("\n\tENTER THE NUMBER TO BE PUSHED: ");
p=(struct stack*)malloc(sizeof (struct stack));
scanf("%d",&p->number);
p->next=NULL;
if(top==NULL)
{
top=p;
}
else
{
p->next=top;
top=p;
}
}
Linked list-based Stack Implementation continue…..

1.Perform pop operation,


a. initialize one variable as int x.
b. check stack is empty or not. i.e. top== NULL or not.
c. if not, p=top;
- take data of top in the variable x,
x=top->number,

- point top node to next node, for making next node as


top, top=top->next
- free p node.
- print which data is popped from stack using x.
Pop Operation
int pop() /*FUNCTION FOR POPPING ELEMENTS*/
{
int x;
if(top==NULL)
{
printf("\n\tTHE STACK IS EMPTY!");
return 0;
}
else
{
p=top;
x=top->number;
top=top->next;
free(p);
return x;
}
}
Linked list-based Stack Implementation continue…..

Display the stack


a. check stack is empty or not. i.e. top== NULL or not.
b. if not, q = top
c. print the data of q->number till q->next not equal to NULL.
Display Operation
void display() /*FUNTION FOR DIPLAYING ELEMENTS*/
{
if (top==NULL)
{
printf("\n\tTHE STACK IS EMPTY!");
}
else
{
q=top;
while(q!=NULL)
{
printf("\n\t%d",q->number);
q=q->next;
}
}
}
In implementation of stack
using linked list

 Push operation is same as insertion at


front in SLL.
 Pop operation is same as deletion at front
in SLL.
Stack using Stack using
array linked list

Stack empty
top == -1 top == NULL
condition

Stack full top == MAX-1 malloc function


returns NULL when
condition heap memory is full.
Then stack full
condition occurs.
Disadvantages of stack :
1.Insertion and deletion of element can be performed by only one
end.
2.The element being inserted first has to wait.
3.Only the element at the top can be deleted at a time.

Programs:
1.1. Convert a decimal number to binary using stack.
2.2. Reverse the string using stack.
3.3. Check whether the a given string is palindrome or not.
Applications of Stacks
1.Nested parenthesis check or parenthesis
Matching
2.Expression evaluation
3.The underlying structure for recursion
4.Function calls (and its associated variables)
Real-time Uses of Stacks
• The runtime stack used by a
process (running program) to
keep track of methods in
progress
• Search problems
• Undo, redo, back, forward
Mathematical Calculations
• What does 3 + 2 * 4 equal?
or 10 / 2 + 5

• The precedence of operators affects the order of operations.


• Also parenthesis affects the order of operations.
• A mathematical expression cannot simply be evaluated left to right.
• A challenge when evaluating a program.

So, above equation can be written as


(3+2)*4 or 3+(2*4)

The way we are use to writing expressions is known as infix notation

What about 1 - 2 - 4 ^ 5 * 3 * 6 / 7 ^ 2 ^ 3
Application of stack-
Expression Evaluation and conversion
Consider an expression - A + B
Operand Operand

Operator

• ‘+ ’ is the operator that is going to perform addition operation on two operands


‘A’ and ‘B’.

Three Different notations for writing an Expressions:-


1.Infix Expression or Infix notation:
2.Postfix Expression or Postfix notation or Reverse Polish Notations:
3.Prefix Expression or Prefix notation: or Polish Notations
1.Infix Expression:
Infix expression = operand1 operator operand2
• Parenthesis can be used in these Expressions.
• Infix expression are the most natural way of representing the expressions.

1.Postfix Expression: Reverse Polish Notations


Postfix expression = operand1 operand2 operator
• No Parenthesis is used.
• All corresponding operands come first and then operator can placed.

1.Prefix Expression:Polish Notations


Prefix expression = operator operand1 operand2
• No Parenthesis is used.
• All corresponding operators come first and then operands are arranged.
• Examples:
Sr. No. Infix Postfix Prefix

1. a+b ab+ +ab

2. (a+b)*(c-d) ab+cd-* *+ab-cd

3. (a+b/e)*(d+f) abe/+df+* *+a/be+df

Evaluation of an Expression:
• To evaluate an infix Expression, we need the precedence and associativity
of the operators And which is very complex task.
• But what is do we mean by associativity?
Let us consider an example A+B+C. In this example the operators are
of same precedence, so whether to start with A+B or B+C. To resolve this
conflict we need to know the associativity of the operators i.e. whether to
start from left to right or from right to left.
Precedence And associativity
Operation Precedence Associativity Example

Exponential(^or High R-L 3^2^2= Here first 2^2 is evaluated i.e.


$) 4 then 3^4is evaluated

Multiplication Intermediate L-R 4/2*2= Here first 4/2 is evaluated i.e.


(*)/ Division(/) 2 then 2*2 is evaluated i.e. 4

Addition(+)/ Low L-R 3+4-2= Here first 3+4 is evaluated i.e.


subtraction(-) 7 then 7-2 is evaluated i.e. 5
1. Conversion of Infix expression to postfix and
prefix
1.a+b
2.a+b-c
3.a*b/(c*d^e)
4.a^b*c-d+e/f/(g+h)
5.((a+b)*c-(d-e))^(f+g)

2. Conversion of postfix expression to infix and


prefix
1.ab+c-
2.abc^/de*+ac-/
3.abc-+de-fg-h+/*
3. Conversion of prefix expression to infix and
postfix
1.-+abc
2.-+/a^bc*de*ac
Evaluation of a postfix expression using
stack
Algorithm:
1.Read the postfix expression from left to right.
2.If the input symbol read is an operand then push it onto stack.
3.If the operator is read pop two operands & perform arithmetic
operations, if operator is->
+ the result = operand1 + operand2
- the result = operand1 - operand2
* the result = operand1 * operand2
/ the result = operand1 / operand2
$ the result = pow(operand1,operand2)
1.Push the result onto stack.
2.Repeat steps 1 to 4 till postfix expression is not over.
3. Pop the evaluated output from stack and display it.
Evaluation of a postfix expression
using stack
Example:

1. 653+9*+
2. ab*c+d-e+
where, a=5,b=4,c=10,d=15 & e=6

Note: In evaluation method,


Stack is called as “Operand stack”, since it only contain operands
as an elements.
1. 653+9*+
Input Content of Operation op1 op2 result
Symbol stack

No empty - - - -
symbol
6 6 push(6) - - -
5 6,5 push(5)

3 6,5,3 push(3)

+ 6,8 Pop top element and store in op2, 5 3 8


Pop top element and store in op1
Perform the operation op1+op2 and push result
on stack

9 6,8,9 push(9) - - -
* 6,72 Pop top element and store in op2, 8 9 72
Pop top element and store in op1
Perform the operation op1*op2 and push result
on stack

+ 78 Pop top element and store in op2, 6 72 78


Pop top element and store in op1
Perform the operation op1+op2 and push result
on stack

- 78 Final result - - -
1.2. ab*c+d-e+ where, a=5,b=4,c=10,d=15 & e=6
Input Content of stack Operation op1 op2 result
Symbol
No empty - - - -
symbol
a=5 5 push(5) - - -
b=4 5,4 push(4)

* 20 Pop top element and store in op2, 5 4 20


Pop top element and store in op1
Perform the operation op1*op2 and push result
on stack
c=10 20,10 push(10) - - -
+ 30 Pop top element and store in op2, 20 10 30
Pop top element and store in op1
Perform the operation op1+op2 and push result
on stack
d=15 30,15 push(15) - - -
- 15 Pop top element and store in op2, 30 15 15
Pop top element and store in op1
Perform the operation op1-op2 and push result
on stack
e=6 15,6 push(6) - - -
+ 21 Pop top element and store in op2, 15 6 21
Pop top element and store in op1
Perform the operation op1+op2 and push result
Conversion of an infix expression to postfix using
stack
Certain rules which has to followed while converting infix to postfix form:
1.Read the expression from left to right.
2.Make use of stack to store the operators.

Algorithm:

1.Read the expression from left to right.


2.If the input symbol read is ‘(‘ then push it onto the stack.
3.If the input symbol read is an operand then place it in output (postfix
expression).
Conversion of an infix expression to postfix using
stack
4. If the input symbol read is an operator then
(a). check if the precedence of the operator which is in the stack has
greater precedence than the operator read, is so then remove that symbol
from the stack & place it in the output.
Repeat step 4. (a) till you get the operator in the stack has
greater precedence than the operator being read.
(b). Otherwise push the operator being read onto stack.

5. If the input symbol read is a closing parenthesis ‘)’ then pop all operators
from the stack, place them in output till the opening parenthesis is not
popped. So pop ‘(‘ & discard it.

6. If the end of input string is encountered, then iterate the loop until stack is
not empty. Pop the stack elements and append the remaining input string to
the output.
Examples:
1. a*b+c
2. a*b/(c-d)+e*(f-g)

Note: In conversion method,


Stack is called as “Operator stack”, since it only contain operator as
an elements.
a*b+c

Input Content of Postfix Operation


Symbol stack Expression
No symbol empty ---- Stack is empty
a empty a Operand present add in postfix exp.
* * a * operator come, push on stack
b * ab Operand present add in postfix exp.
+ + ab* + operator come, but * has higher precedance
so pop it and add in postfix exp. and push + on
stack

c + ab*c Operand present add in postfix exp.


--- empty ab*c+ No operad available, pop all element present in
stack and add them in postfix exp.
a*b/(c-d)+e*(f-g)
Input Content Postfix Operation
Symbol of stack Expression
No empty ---- Stack is empty
symbol
a empty a Operand present add in postfix exp.

* * a * operator come, push on stack

b * ab Operand present add in postfix exp.

/ / ab* / operator come, * and / has same precedance so


pop * and push / on stack according to assossivity
rule
( /( ab* Opening bracket, push on stack

c /( ab*c Operand present add in postfix exp.

- /(- ab*c - operator come, push on stack

d /(- ab*cd Operand present add in postfix exp.

) / ab*cd- Closing bracket come, pop operators and add to


postfix exp. Till opening bracket encountered and
+ + ab*cd-/ + operator come, but / has higher precedance
so pop it and add in postfix exp. and push + on
stack
e + ab*cd-/e Operand present add in postfix exp.

* +* ab*cd-/e * operator come, push on stack

( +*( ab*cd-/e Opening bracket, push on stack

f +*( ab*cd-/ef Operand present add in postfix exp.

- +*(- ab*cd-/ef - operator come, push on stack

g +*(- ab*cd-/efg Operand present add in postfix exp.

) +* ab*cd-/efg- Closing bracket come, pop operators and add to


postfix exp. till opening bracket encountered and
discard the opening bracket
--- empty ab*cd-/efg-*+ No operad available, pop all element present in
stack and add them in postfix exp.
Removal of Recursion Using Stack
int fact(int n)
{
struct stack s;
int val;
while(n>0)
{ push (&s,n);
n=n-1;
}
val=1;
while( !empty(&s) )
{ val=val*pop(&s);
}
return(val);
}

You might also like