SlideShare a Scribd company logo
Chapter 4
Stack
Definition of Stack
• Stack is a linear data structure which follows a particular order in which the
operations are performed. The order may be LIFO(Last In First Out) or
FILO(First In Last Out).
• There are many real-life examples of a stack. Consider an example of plates
stacked over one another in the canteen. The plate which is at the top is the
first one to be removed, i.e. the plate which has been placed at the
bottommost position remains in the stack for the longest period of time. So,
it can be simply seen to follow LIFO(Last In First Out)/FILO(First In Last
Out) order.
Basic Operations
on Stack
• push() − Pushing (storing) an element on the stack.
• pop() − Removing (accessing) an element from the stack.
Basic Operations
on Stack
• To use a stack efficiently, we need to check the status of stack as well. For
the same purpose, the following functionality is added to stacks −
• peek() − get the top data element of the stack, without removing it.
• isFull() − check if stack is full.(Overflow) -push
• isEmpty() − check if stack is empty.(underflow)-pop
Push Operation
• The process of putting a new data element onto stack is known as a Push
Operation. Push operation involves a series of steps −
• Step 1 − Checks if the stack is full.
• Step 2 − If the stack is full, produces an error and exit.
• Step 3 − If the stack is not full, increments top to point next empty space.
• Step 4 − Adds data element to the stack location, where top is pointing.
• Step 5 − Returns success.
Push Operation
Procedure for Push Operation
begin procedure push: stack, data
if stack is full
return null
endif
top ← top + 1
stack[top] ← data
end procedure
Code for Push Operation
void push(int data) {
if(!isFull()) {
top = top + 1;
stack[top] = data;
} else {
printf("Could not insert data, Stack is full.n");
}}
Pop Operation
• Accessing the content while removing it from the stack, is known as a Pop
Operation. In an array implementation of pop() operation, the data element
is not actually removed, instead top is decremented to a lower position in the
stack to point to the next value. But in linked-list implementation, pop()
actually removes data element and deallocates memory space.
Pop Operation
• A Pop operation may involve the following steps −
• Step 1 − Checks if the stack is empty.
• Step 2 − If the stack is empty, produces an error and exit.
• Step 3 − If the stack is not empty, accesses the data element at which top is
pointing.
• Step 4 − Decreases the value of top by 1.
• Step 5 − Returns success.
Pop Operation
Algorithm for Pop Operation
begin procedure pop: stack
if stack is empty
return null
endif
data ← stack[top]
top ← top - 1
return data
end procedure
Code for Pop
int pop(int data) {
if(!isempty()) {
data = stack[top];
top = top - 1;
return data;
} else {
printf("Could not retrieve data, Stack is empty.n");
}
}
Algorithm for isfull()
int isfull() {
if(top == MAXSIZE)
return 1;
else
return 0;
}
Algorihm for isempty()
begin procedure isempty
if top less than 1
return true
else
return false
endif
end procedure
Code for isempty()
int isempty() {
if(top == -1)
return 1;
else
return 0;
}
Applications of Stack
• In a stack, only limited operations are performed because it is restricted data
structure. The elements are deleted from the stack in the reverse order.
Applications of stack:
• Following are the applications of stack:
1. Expression Evaluation
2. Expression Conversion
    i. Infix to Postfix
    ii. Infix to Prefix
    iii. Postfix to Infix
    iv. Prefix to Infix
STACK IMPLEMENTATION:-
• The stack implementation can be done in two ways:-
• 1) Static implementation:-
• It can be achieved using arrays. Though it is very simple method it has few limitations.
• Once a size of an array is declared, its size cannot be modified during program
execution.
• The vacant space of stack also occupies memory space.
• In both cases, if we store less argument than declared, memory is wasted and if we want
to store more
• elements than declared array cannot be expanded. It is suitable only when we exactly
know the number of
• elements to be stored.
Operations on static stack:-
• 1) Declaring of a stack :-
• A stack to be implemented using an array will require.
• - An array of a fixed size.
• - An integer called top which stored the index or position of the topmost element.
• We can use a structure for the above purpose.
• 2) Creating a stack:-
• This declaration only specifies the template. The actual stack can be declared as-
• STACK s1;
• 3) initialize a stack:-
• When a stack variable is declared the integer top has to be initialized to indicate an empty stack. Since we
• are using an array the first element will occupy position 0. Hence to indicate an empty stack top has to be
• initialized to -1
• 4) Checking whether stack is empty:-
• An empty stack can be tested from the value contained in top. If top contains -1 it indicates an
• empty stack.
• 5) Checking whether stack is full:-
• If the value of top reaches the maximum array index i.e. MAX-1 no more elements can be pushed into the
• stack.
• 6) The push operation:-
• The element can be pushed into the stack only if it is not full. In such case the top has to be incremented
• first and the element has to be put in this position.
• 7) The pop operation:
• An element can be removed from the stack if it is not empty. The topmost element can be removed after
• which top has to decremented
(ststack.h file
• #define MAX 60
• struct stack
• {
• int top;
• int item[MAX];
• };
• typedef struct stack STACK;
• void initstack(STACK *s)
• {
• s->top=-1;
• }
• int isempty(STACK *s)
• if (s->top==-1)
• return(1);
• else
• return(0);
• }
• int isfull(STACK *s)
• {
• if (s->top==MAX-1)
• return(1);
• else
• return(0);
• }
• void push(STACK *s,int data)
• {
• ++s->top;
• s->item[s->top]=data;
• }
• int pop(STACK *s)
• {
• return(s->item[s->top--]);
• }
• void display(STACK *s)
• {
• int i;
• for(i=0;i<=s->top;i++)
• printf("%dt",s->item[i]);
• }
• int peek(STACK *s)
• {
• return(s->item[s->top]);
• }
.c file
• #include<stdio.h>
• #include<stdlib.h>
• #include "ststack.h"
• main()
• {
• STACK s;
• int data,ch;
• initstack(&s);
• while(1)
• {
• printf("nnMain Menu");
• printf("n1 : PUSH");
• printf("n2 : POP");
• printf("n3 : PEEK");
• printf("n4 : DISPLAY");
• printf("n5 : EXIT");
• printf("nEnter the choice=> ");
• scanf("%d",&ch);
• switch(ch)
• {
• case 1:
• if (isfull(&s))
• printf("nStack is full");
• else
• {
• printf("nEnter the data to be pushed-> ");
• scanf("%d",&data);
• push(&s,data);
• }
• break;
• case 2:
• if(isempty(&s))
• printf("nStack is empty");
• else
• printf("nPopped data is %d",pop(&s));
• break;
• case 3:
• if(isempty(&s))
• printf("nTop element cannot be displayed: ");
• else
• printf("nTop element of the stack: %d",peek(&s));
• break;
• case 4:
• if(isempty(&s))
• printf("nstack is empty");
• else
• display(&s);
• break;
• case 5:
• exit(1);
Dynamic implementation
• Pointers are used for implementation of stack. The linked list is an e.g. of this implementation.
• The limitations noticed in static implementation can be removed using dynamic implementation. The
• dynamic implementation is achieved using pointers.
• Using pointer implementation at runtime there is no restriction on the no. of elements. The stack may be
• expandable.
• The memory is efficiently utilized with pointers.
• Memory is allocated only after element is pushed to the stack
• In static representation there is a limitation on the size of the array if less elements are stored, memory will
• be wasted. To overcome the program the stack can be implemented using linked list.
• In the linked organization
• - The stack can grow to any size.
• - We need not have prior knowledge of the number of elements.
• When an element is popped the memory can be freed. Thus memory is not unnecessary occupied.
• Since random access to any element is not required in a stack, the linked representation is preferred over
• the sequential organization.
dystack.h file
• #define MAX 20
• struct node
• {
• int data;
• struct node *next;
• };
• typedef struct node NODE;
• NODE *top;
• NODE * alloc(int data)
• {
• NODE *temp;
• temp=(NODE*)malloc(sizeof(NODE));
• temp->data=data;
• temp->next=NULL;
• return(temp);
• }
• int isempty()
• {
• if (top==NULL)
• return(1);
• else
• return(0);
• }
• void push(int data)
• {
• NODE *temp;
• temp=alloc(data);
• temp->next=top;
• top=temp;
• }
• int pop()
• {
• NODE *temp;
• int val;
• temp=top;
• val=temp->data;
• top=top->next;
• free(temp);
• return(val);
• }
• int peek()
• {
• NODE *temp;
• int val;
• temp=top;
• val=temp->data;
• return(val);//return(temp->data)
• }
• void display()
• {
• NODE *ptr;
• for(ptr=top;ptr->next!=NULL;ptr=ptr->next)
• printf("%d ",ptr->data);
• printf("%d",ptr->data);
• }
(.c file)
• #include<stdio.h>
• #include<stdlib.h>
• #include "dystack.h"
• main()
• {
• int data,ch;
• while(1)
• {
• printf("nnMain Menu");
• printf("n1 : PUSH");
• printf("n2 : POP");
• printf("n3 : PEEK");
• printf("n4 : DISPLAY");
• printf("n5 : EXIT");
• printf("nEnter the choice=> ");
• scanf("%d",&ch);
• switch(ch)
• {
• case 1:
• printf("nEnter the data to be pushed-> ");
• scanf("%d",&data);
• push(data);
• break;
• case 2:
• if(isempty())
• printf("nStack is empty");
• else
• printf("nPopped data is %d",pop());
• break;
• case 3:
• if(isempty())
• printf("nTop element cannot be displayed: ");
• else
• printf("nTop element of the stack: %d",peek());
• break;
• case 4:
• if(isempty())
• printf("nstack is empty");
• else
• display();
• break;
• case 5:
• exit(1);
• }
• }
• }
Infix expression
• Infix, Postfix and Prefix notations are three different but equivalent ways of
writing expressions. It is easiest to demonstrate the differences by looking at
examples of operators that take two operands.
• Infix notation: X + Y
• Operators are written in-between their operands. This is the usual way we
write expressions. An expression such as A * ( B + C ) / D is usually taken to
mean something like: "First add B and C together, then multiply the result by
A, then divide by D to give the final answer."
• Expression consists of operators and operands
• Operands= It is identifier or constants.
• Operator= It is symbols (+,-,/,*)
• A+B=C
• Operators(+,=) operands(A,B,C)
Infix expression
• The operand is placed between the operands
• Infix notation needs extra information to make the order of evaluation of the
operators clear: rules built into the language about operator precedence and
associativity, and brackets ( ) to allow users to override these rules. For
example, the usual rules for associativity say that we perform operations from
left to right, so the multiplication by A is assumed to come before the
division by D. Similarly, the usual rules for precedence say that we perform
multiplication and division before we perform addition and subtraction
Postfix notation
• Postfix notation (also known as "Reverse Polish notation"): X+Y =X Y +
• Operators are written after their operands. The infix expression given above
is equivalent to A B C + * D /
• The order of evaluation of operators is always left-to-right, and brackets
cannot be used to change this order. Because the "+" is to the left of the "*"
in the example above, the addition must be performed before the
multiplication.
Postfix notation
• Operators act on values immediately to the left of them. For example, the
"+" above uses the "B" and "C". We can add (totally unnecessary) brackets
to make this explicit:
• ( (A (B C +) *) D /)
• Thus, the "*" uses the two values immediately preceding: "A", and the result
of the addition. Similarly, the "/" uses the result of the multiplication and the
"D".
Prefix notation
• Prefix notation (also known as "Polish notation"): X+Y=+ X Y
• Operators are written before their operands. The expressions given above are
equivalent to / * A + B C D
• As for Postfix, operators are evaluated left-to-right and brackets are
superfluous. Operators act on the two nearest values on the right. I have
again added (totally unnecessary) brackets to make this clear:
• (/ (* A (+ B C) ) D)
Chapter 4 stack
INFIX TO POSTFIX CONVERSION
Algorithm
1) Scan the string from left to right
2) Make three columns symbol , postfix expression and stack
3) If symbol = = opening bracket push in stack (i.e put in stack column)
INFIX TO POSTFIX CONVERSION
4) If symbol = = closing bracket pop all the elements from stack till we get
opening bracket, pop the opening bracket also and then put the pop elements
in the postfix expression column leaving opening bracket.
5) If symbol = = alphabet/ digit then put the symbol in postfix expression
column
6) If symbol = = operator check priority of top element in the stack.
INFIX TO POSTFIX CONVERSION
If priority( top element)>= priority(symbol operator) then pop top element and
put it in postfix expression column If priority( top element)< priority(symbol
operator) then push the symbol in the stack
7) If all the symbol finished from the symbol pop all the elements from stack
and put it in postfix expression column
INFIX TO POSTFIX CONVERSION
3+4*5/6
Symbol Postfix Expression Stack Remark
3 3 Step 5
+ 3 + Step 6
4 3 4 + Step 5
* 3 4 + * Step 6
5 3 4 5 + * Step 5
/ 3 4 5 * + / Step 6
6 3 4 5 * 6 + / Step 5
0 3 4 5 * 6 / + Step 7
A^B*C-D+E/F/(G+H)
Symbol Postfix Expression Stack Remark
A A Step 5
^ ^ Step 6
B AB ^ Step 5
* AB^ * Step 6
C AB^C * Step 5
- AB^C* - Step 6
D AB^C*D - Step 5
+ AB^C*D- + Step 6
E AB^C*D-E + Step 5
/ AB^C*D-E +/ Step 6
F AB^C*D-EF +/ Step 5
/ AB^C*D-EF/ +/ Step 6
A^B*C-D+E/F/(G+H)
Symbol Postfix Expression Stack Remark
( AB^C*D-EF/ +/( Step 3
G AB^C*D-EF/G +/( Step 5
+ AB^C*D-EF/G +/(+ Step 6
H AB^C*D-EF/GH +/(+ Step 5
) AB^C*D-EF/GH+ +/ Step 4
0 AB^C*D-EF/GH+/+ Step 7
Infix to Postfix
( ( A + B ) — C * ( D / E ) ) + F
Infix to Postfix
• A* B+C,A+B*C,(A+B)*(C-D),A*B-C$D+E
Symbol Postfix Expression Stack Remark
A A
* A *
B AB *
+ AB* +
C AB*C +
0 AB*C+
INFIX TO PREFIX CONVERSION
Algorithm
1) Scan the string from right to left
2) Make three columns symbol , prefix expression and stack
3) If symbol = = closing bracket push in stack (i.e put in stack column)
INFIX TO PREFIX CONVERSION
4) If symbol = = opening bracket pop all the elements from stack till we get
closing bracket, pop the closing bracket also and then put the pop elements in
the postfix expression column leaving closing bracket.
5) If symbol = = alphabet/ digit then put the symbol in prefix expression
column
6) If symbol = = operator check priority of top element in the stack. If priority(
top element)> priority(symbol operator) then pop top element and put it in
prefix expression column
INFIX TO PREFIX CONVERSION
If priority( top element)<= priority(symbol operator) then push the symbol in
the stack
7) If all the symbol finished from the symbol pop all the elements from stack
and put it in prefix expression column
8) Reverse the final string
A+B*(C^(D-E)+F)-G
Symbol Prefix Expression Stack Remark
G G Step 5
- G - Step 6
) G - ) Step 3
F GF - ) Step 5
+ GF -)+ Step 6
) GF -)+) Step 6
E GFE -)+) Step 5
- GFE -)+)- Step 6
D GFED -)+)- Step 5
( GFED- -)+ Step 4
^ GFED- -)+^ Step 6
C GFED-C -)+^ Step 5
( GFED-C^+ - Step 4
Symbol Prefix Expression Stack Remark
* GFED-C^+ - * Step 6
B GFED-C^+B - * Step 5
+ GFED-C^+B * - + Step 6
A GFED-C^+B * A - + Step 5
0 GFED-C^+B * A + - Step 7
Reverse the Prefix Expression:- The Result will be
- +A * B + ^ C - DEFG
A * B + C / D
Symbol Prefix expression Stack Remark
D D Step 5
/ D / Step 6
C DC / Step 5
+ DC/ + Step 6
B DC/B + Step 5
* DC/B + * Step 6
A DC/BA + * Step 5
0 DC/BA*+ +*AB/CD
(A+B)*(C-D)
Symbol Prefix expression Stack Remark
) )
D D )
- D )-
C DC )-
( DC-
* DC- *
) DC- *)
B DC-B *)
+ DC-B *)+
A DC-BA *)+
( DC-BA+* *+AB-CD
1. A*B+C
2. A+B*C
3. A*B-C$D+E
4. A+(B-C*D)-E/F$G
Chapter 4 stack
Steps to convert Postfix to Infix Expression
Step 1:- Scan the postfix expression from left to right.
Step 2:- Initialize an empty string stack.
Step 3:- If the scanned character is operand, push it into stack.
Step 4:- Else if the scanned character is operator, pop two operands from stack, and add
this Operator in between the two operands. namely, opd1 and opd2, and 
push: (opd1 operator op2) into stack.
Step 5:- Repeat steps from 3 to 4 until all the characters from the string are scanned.
Step 6:-In the end, only one valid infix string will be present in the stack, pop it and return
it.
AB-DE+F*/
Symbol Stack Remark
A A Step 3
B AB Step 3
- (A-B) Step 4
D (A-B)D Step 3
E (A-B)DE Step 3
+ (A-B)(D+E) Step 4
F (A-B)(D+E)F Step 3
* (A-B)(D+E)*F Step 4
/ (A-B)/((D+E)*F) Step 4
ab+c*
Symbol Stack Remark
a a Step 3
b ab Step 3
+ (a+b) Step 4
c (a+b) c Step 3
* ((a+b) * c) Step 4
SIMULATING STACK USING RECURSION
1)A procedure is called recursive if the procedure is defined by itself. i.e. when a
function is defined in terms of itself then it is called a recursive.
2) In the recursion, the procedure calls itself directly or indirectly.
Directly means functions called itself repeatedly. Indirectly means a function calls
the another function. Hence the functions are executed repeatedly, every time a
new value is passed to the recursive function till the condition is satisfied. If the
recursive procedure calls itself then current values of parameters must be saved,
since they will be used again when a program is reactivated.
RECURSION
3) Rules:
There must be terminating condition to stop recursion.
When function is called recursively the copy of the stack is maintain.
E.g. Consider the definition of factorial of a positive integer n.
fact(n)= 1 if(n==0)
n*fact(n-1) otherwise
RECURSION
int fact(int n)
{
if(n==0)
return 1;
else
return(n*fact(n));
}
RECURSION
• Function fact() is defined in terms of itself for n>0.
• Value of the function at n=0 is 1 and it is called the base. Recursion
terminates on reaching the base.
* Removal of Recursion (using stack) Any recursive function can be converted
to non recursive function through use of a stack.
1) A recursive call is similar to a call to another function.
2) Any call to a function requires that the function has storage area where it can
store its local variables and actual parameters.
3) Return address must be saved before a call is made to a function.
4) Storage area for local variables, actual parameters and the return address can be
provided through a stack.
5) In case of a recursive call, the value of local variables, parameters and the return
address must be saved on the stack.
6) While returning from a nested call, the previous outer call must be recalled with
resetting all the local variables and operation must resume from where it was
suspended
Rules for converting a recursive algorithm to
non recursive one-
• 1) Declare stack-: It will hold local variables, parameters, return address etc.
2) The first statement after the stack initialization must have a label
• Steps required to replace a recursive call 1) Push all local variables and
parameters into the stack 2) Push an integer i into stack i gives the return
address. 3) Set the values of formal parameters 4) Transfer the control to the
beginning of the function (i.e first label immediately after initialization of
stack) 5) There should always be a label statement immediately following the
recursive call This label is the return address
Rules for converting a recursive algorithm to
non recursive one-
Steps required at the end of recursion function
1) If the stack is empty , then the recursion is finished
2) Otherwise pop the stack to restore the values of all local variables and
parameters called by value
3) Pop the return address
Back Tracking
• It Can be used to solve NP-Complete problems such as 0-1 Knapsack more
efficiently
• Backtracking vs Dynamic Programming
• Dynamic Programming – subsets of a solution are generated Backtracking
– Technique for deciding that some subsets need not be generated
• Efficient for many large instances of a problem (but not all)
• Backtracking Technique
• Solve problems in which a sequence of objects is chosen from a set
Sequence satisfies some criterion
• Modified DFS of a rooted tree Pre-order traversal
• General-purpose algorithm does not specify order children visited – we
will use left to right
• N-Queen Problem
• Goal: position n queens on a n x n board such that no two queens
threaten each other
• No two queens may be in the same row, column, or diagonal Sequence: n
positions where queens are placed
• Set: n2 positions on the board
• Criterion: no two queens threaten each other
• Place Q1 Q2 Q3 bracktrack,place Q2
1 2 3 4
1 Q
2
3
4 1,1
1 2 3 4
1 Q
2 X X Q
3
4
2,3
1,1
1 2 3 4
1 Q
2 Q
3 X X X X
4
1 2 3 4
1 Q
2 Q
3
4
2,3
1,1
2,4
1,1
• Place Q3 Q4 BT,Q3,Q2,Q1 Q2
1 2 3 4
1 Q
2 Q
3 X Q
4
1 2 3 4
1 Q
2 Q
3 Q
4 X X X X
1 2 3 4
1 Q
2
3
4
1 2 3 4
1 Q
2 Q
3
4
2,4
1,2
1,2
3,2
2,4
1,1
3,2
2,4
1,1
• Place Q3 Q4
1 2 3 4
1 Q
2 Q
3 Q
4
1 2 3 4
1 Q
2 Q
3 Q
4 X X Q
3,1
2,4
1,2
4,3
3,1
2,4
1,2
Chapter 4 stack

More Related Content

PPTX
Operation on stack
PPT
03 stacks and_queues_using_arrays
PPT
Stacks and queue
PPT
Stack Operation In Data Structure
PPTX
Queue Data Structure (w/ php egs)
PPT
Stack Implementation
PPT
Data structure lecture7
Operation on stack
03 stacks and_queues_using_arrays
Stacks and queue
Stack Operation In Data Structure
Queue Data Structure (w/ php egs)
Stack Implementation
Data structure lecture7

What's hot (20)

PPT
stack and queue array implementation in java.
PDF
PPTX
Stack - Data Structure
PPT
Lecture 2d queues
PDF
Stacks
PPTX
Queues
PPT
Stack Data Structure V1.0
PPTX
Mcs011 solved assignment by divya singh
PPT
Queue implementation
PPT
PPT
Queue data structure
PPT
Algorithm: priority queue
PPTX
Queue Implementation Using Array & Linked List
PPTX
Stack data structure
PPT
Data structures
PPT
Priority queues
PDF
PPSX
Queue by rajanikanth
PDF
Data structures stacks
PPT
Notes DATA STRUCTURE - queue
stack and queue array implementation in java.
Stack - Data Structure
Lecture 2d queues
Stacks
Queues
Stack Data Structure V1.0
Mcs011 solved assignment by divya singh
Queue implementation
Queue data structure
Algorithm: priority queue
Queue Implementation Using Array & Linked List
Stack data structure
Data structures
Priority queues
Queue by rajanikanth
Data structures stacks
Notes DATA STRUCTURE - queue
Ad

Similar to Chapter 4 stack (20)

PPT
Stacks
PPTX
The presentation on stack data structure
PPTX
Stack,queue and linked list data structure.pptx
PDF
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
PPTX
DS-UNIT 3 FINAL.pptx
PPTX
Stack and its Applications : Data Structures ADT
PPT
stack and queue array implementation, java.
PPTX
DATA STRUCTURE AND COMPUTER ALGORITHMS LECTURE 2
PDF
Chapter 5 Stack and Queue.pdf
PPTX
DSEC1.pptx stack exchange communities that I am not 🚭 hi nahi
PPTX
6 - STACKS in Data Structure and Algorithm.pptx
PPT
Stack in Data Structure
PPTX
STACKS implimentarions AND stack applications .pptx
PPTX
DS UNIT 2 PPT.pptx stack queue representations
PDF
notes.pdf
PPTX
Chapter 5-stack.pptx
PPTX
Stack and Queue.pptx university exam preparation
PPTX
5.-Stacks.pptx
PPT
week 7,8,10,11 alll files included from .ppt
PPTX
stack_operationss_documentation_file.ppt
Stacks
The presentation on stack data structure
Stack,queue and linked list data structure.pptx
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
DS-UNIT 3 FINAL.pptx
Stack and its Applications : Data Structures ADT
stack and queue array implementation, java.
DATA STRUCTURE AND COMPUTER ALGORITHMS LECTURE 2
Chapter 5 Stack and Queue.pdf
DSEC1.pptx stack exchange communities that I am not 🚭 hi nahi
6 - STACKS in Data Structure and Algorithm.pptx
Stack in Data Structure
STACKS implimentarions AND stack applications .pptx
DS UNIT 2 PPT.pptx stack queue representations
notes.pdf
Chapter 5-stack.pptx
Stack and Queue.pptx university exam preparation
5.-Stacks.pptx
week 7,8,10,11 alll files included from .ppt
stack_operationss_documentation_file.ppt
Ad

Recently uploaded (20)

PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
Cell Types and Its function , kingdom of life
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
RMMM.pdf make it easy to upload and study
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Module 4: Burden of Disease Tutorial Slides S2 2025
STATICS OF THE RIGID BODIES Hibbelers.pdf
Week 4 Term 3 Study Techniques revisited.pptx
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
TR - Agricultural Crops Production NC III.pdf
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Microbial diseases, their pathogenesis and prophylaxis
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
O7-L3 Supply Chain Operations - ICLT Program
Renaissance Architecture: A Journey from Faith to Humanism
Cell Types and Its function , kingdom of life
102 student loan defaulters named and shamed – Is someone you know on the list?
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPH.pptx obstetrics and gynecology in nursing
Final Presentation General Medicine 03-08-2024.pptx
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
RMMM.pdf make it easy to upload and study
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...

Chapter 4 stack

  • 2. Definition of Stack • Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). • There are many real-life examples of a stack. Consider an example of plates stacked over one another in the canteen. The plate which is at the top is the first one to be removed, i.e. the plate which has been placed at the bottommost position remains in the stack for the longest period of time. So, it can be simply seen to follow LIFO(Last In First Out)/FILO(First In Last Out) order.
  • 3. Basic Operations on Stack • push() − Pushing (storing) an element on the stack. • pop() − Removing (accessing) an element from the stack.
  • 4. Basic Operations on Stack • To use a stack efficiently, we need to check the status of stack as well. For the same purpose, the following functionality is added to stacks − • peek() − get the top data element of the stack, without removing it. • isFull() − check if stack is full.(Overflow) -push • isEmpty() − check if stack is empty.(underflow)-pop
  • 5. Push Operation • The process of putting a new data element onto stack is known as a Push Operation. Push operation involves a series of steps − • Step 1 − Checks if the stack is full. • Step 2 − If the stack is full, produces an error and exit. • Step 3 − If the stack is not full, increments top to point next empty space. • Step 4 − Adds data element to the stack location, where top is pointing. • Step 5 − Returns success.
  • 7. Procedure for Push Operation begin procedure push: stack, data if stack is full return null endif top ← top + 1 stack[top] ← data end procedure
  • 8. Code for Push Operation void push(int data) { if(!isFull()) { top = top + 1; stack[top] = data; } else { printf("Could not insert data, Stack is full.n"); }}
  • 9. Pop Operation • Accessing the content while removing it from the stack, is known as a Pop Operation. In an array implementation of pop() operation, the data element is not actually removed, instead top is decremented to a lower position in the stack to point to the next value. But in linked-list implementation, pop() actually removes data element and deallocates memory space.
  • 10. Pop Operation • A Pop operation may involve the following steps − • Step 1 − Checks if the stack is empty. • Step 2 − If the stack is empty, produces an error and exit. • Step 3 − If the stack is not empty, accesses the data element at which top is pointing. • Step 4 − Decreases the value of top by 1. • Step 5 − Returns success.
  • 12. Algorithm for Pop Operation begin procedure pop: stack if stack is empty return null endif data ← stack[top] top ← top - 1 return data end procedure
  • 13. Code for Pop int pop(int data) { if(!isempty()) { data = stack[top]; top = top - 1; return data; } else { printf("Could not retrieve data, Stack is empty.n"); } }
  • 14. Algorithm for isfull() int isfull() { if(top == MAXSIZE) return 1; else return 0; }
  • 15. Algorihm for isempty() begin procedure isempty if top less than 1 return true else return false endif end procedure
  • 16. Code for isempty() int isempty() { if(top == -1) return 1; else return 0; }
  • 17. Applications of Stack • In a stack, only limited operations are performed because it is restricted data structure. The elements are deleted from the stack in the reverse order.
  • 18. Applications of stack: • Following are the applications of stack: 1. Expression Evaluation 2. Expression Conversion     i. Infix to Postfix     ii. Infix to Prefix     iii. Postfix to Infix     iv. Prefix to Infix
  • 19. STACK IMPLEMENTATION:- • The stack implementation can be done in two ways:- • 1) Static implementation:- • It can be achieved using arrays. Though it is very simple method it has few limitations. • Once a size of an array is declared, its size cannot be modified during program execution. • The vacant space of stack also occupies memory space. • In both cases, if we store less argument than declared, memory is wasted and if we want to store more • elements than declared array cannot be expanded. It is suitable only when we exactly know the number of • elements to be stored.
  • 20. Operations on static stack:- • 1) Declaring of a stack :- • A stack to be implemented using an array will require. • - An array of a fixed size. • - An integer called top which stored the index or position of the topmost element. • We can use a structure for the above purpose. • 2) Creating a stack:- • This declaration only specifies the template. The actual stack can be declared as- • STACK s1; • 3) initialize a stack:- • When a stack variable is declared the integer top has to be initialized to indicate an empty stack. Since we • are using an array the first element will occupy position 0. Hence to indicate an empty stack top has to be • initialized to -1
  • 21. • 4) Checking whether stack is empty:- • An empty stack can be tested from the value contained in top. If top contains -1 it indicates an • empty stack. • 5) Checking whether stack is full:- • If the value of top reaches the maximum array index i.e. MAX-1 no more elements can be pushed into the • stack. • 6) The push operation:- • The element can be pushed into the stack only if it is not full. In such case the top has to be incremented • first and the element has to be put in this position. • 7) The pop operation: • An element can be removed from the stack if it is not empty. The topmost element can be removed after • which top has to decremented
  • 22. (ststack.h file • #define MAX 60 • struct stack • { • int top; • int item[MAX]; • }; • typedef struct stack STACK; • void initstack(STACK *s) • { • s->top=-1; • } • int isempty(STACK *s)
  • 23. • if (s->top==-1) • return(1); • else • return(0); • } • int isfull(STACK *s) • { • if (s->top==MAX-1) • return(1); • else • return(0); • } • void push(STACK *s,int data) • { • ++s->top; • s->item[s->top]=data; • }
  • 24. • int pop(STACK *s) • { • return(s->item[s->top--]); • } • void display(STACK *s) • { • int i; • for(i=0;i<=s->top;i++) • printf("%dt",s->item[i]); • } • int peek(STACK *s) • { • return(s->item[s->top]); • }
  • 25. .c file • #include<stdio.h> • #include<stdlib.h> • #include "ststack.h" • main() • { • STACK s; • int data,ch; • initstack(&s); • while(1) • { • printf("nnMain Menu"); • printf("n1 : PUSH"); • printf("n2 : POP"); • printf("n3 : PEEK");
  • 26. • printf("n4 : DISPLAY"); • printf("n5 : EXIT"); • printf("nEnter the choice=> "); • scanf("%d",&ch); • switch(ch) • { • case 1: • if (isfull(&s)) • printf("nStack is full"); • else • { • printf("nEnter the data to be pushed-> "); • scanf("%d",&data); • push(&s,data); • } • break;
  • 27. • case 2: • if(isempty(&s)) • printf("nStack is empty"); • else • printf("nPopped data is %d",pop(&s)); • break; • case 3: • if(isempty(&s)) • printf("nTop element cannot be displayed: "); • else • printf("nTop element of the stack: %d",peek(&s)); • break; • case 4: • if(isempty(&s)) • printf("nstack is empty"); • else • display(&s); • break; • case 5: • exit(1);
  • 28. Dynamic implementation • Pointers are used for implementation of stack. The linked list is an e.g. of this implementation. • The limitations noticed in static implementation can be removed using dynamic implementation. The • dynamic implementation is achieved using pointers. • Using pointer implementation at runtime there is no restriction on the no. of elements. The stack may be • expandable. • The memory is efficiently utilized with pointers. • Memory is allocated only after element is pushed to the stack • In static representation there is a limitation on the size of the array if less elements are stored, memory will • be wasted. To overcome the program the stack can be implemented using linked list. • In the linked organization • - The stack can grow to any size. • - We need not have prior knowledge of the number of elements. • When an element is popped the memory can be freed. Thus memory is not unnecessary occupied. • Since random access to any element is not required in a stack, the linked representation is preferred over • the sequential organization.
  • 29. dystack.h file • #define MAX 20 • struct node • { • int data; • struct node *next; • }; • typedef struct node NODE; • NODE *top; • NODE * alloc(int data) • { • NODE *temp; • temp=(NODE*)malloc(sizeof(NODE)); • temp->data=data; • temp->next=NULL; • return(temp); • }
  • 30. • int isempty() • { • if (top==NULL) • return(1); • else • return(0); • } • void push(int data) • { • NODE *temp; • temp=alloc(data); • temp->next=top; • top=temp; • }
  • 31. • int pop() • { • NODE *temp; • int val; • temp=top; • val=temp->data; • top=top->next; • free(temp); • return(val); • }
  • 32. • int peek() • { • NODE *temp; • int val; • temp=top; • val=temp->data; • return(val);//return(temp->data) • } • void display() • { • NODE *ptr; • for(ptr=top;ptr->next!=NULL;ptr=ptr->next) • printf("%d ",ptr->data); • printf("%d",ptr->data); • }
  • 33. (.c file) • #include<stdio.h> • #include<stdlib.h> • #include "dystack.h" • main() • { • int data,ch; • while(1) • { • printf("nnMain Menu"); • printf("n1 : PUSH"); • printf("n2 : POP"); • printf("n3 : PEEK"); • printf("n4 : DISPLAY"); • printf("n5 : EXIT"); • printf("nEnter the choice=> "); • scanf("%d",&ch);
  • 34. • switch(ch) • { • case 1: • printf("nEnter the data to be pushed-> "); • scanf("%d",&data); • push(data); • break; • case 2: • if(isempty()) • printf("nStack is empty"); • else • printf("nPopped data is %d",pop()); • break;
  • 35. • case 3: • if(isempty()) • printf("nTop element cannot be displayed: "); • else • printf("nTop element of the stack: %d",peek()); • break; • case 4: • if(isempty()) • printf("nstack is empty"); • else • display(); • break; • case 5: • exit(1); • } • } • }
  • 36. Infix expression • Infix, Postfix and Prefix notations are three different but equivalent ways of writing expressions. It is easiest to demonstrate the differences by looking at examples of operators that take two operands. • Infix notation: X + Y • Operators are written in-between their operands. This is the usual way we write expressions. An expression such as A * ( B + C ) / D is usually taken to mean something like: "First add B and C together, then multiply the result by A, then divide by D to give the final answer."
  • 37. • Expression consists of operators and operands • Operands= It is identifier or constants. • Operator= It is symbols (+,-,/,*) • A+B=C • Operators(+,=) operands(A,B,C)
  • 38. Infix expression • The operand is placed between the operands • Infix notation needs extra information to make the order of evaluation of the operators clear: rules built into the language about operator precedence and associativity, and brackets ( ) to allow users to override these rules. For example, the usual rules for associativity say that we perform operations from left to right, so the multiplication by A is assumed to come before the division by D. Similarly, the usual rules for precedence say that we perform multiplication and division before we perform addition and subtraction
  • 39. Postfix notation • Postfix notation (also known as "Reverse Polish notation"): X+Y =X Y + • Operators are written after their operands. The infix expression given above is equivalent to A B C + * D / • The order of evaluation of operators is always left-to-right, and brackets cannot be used to change this order. Because the "+" is to the left of the "*" in the example above, the addition must be performed before the multiplication.
  • 40. Postfix notation • Operators act on values immediately to the left of them. For example, the "+" above uses the "B" and "C". We can add (totally unnecessary) brackets to make this explicit: • ( (A (B C +) *) D /) • Thus, the "*" uses the two values immediately preceding: "A", and the result of the addition. Similarly, the "/" uses the result of the multiplication and the "D".
  • 41. Prefix notation • Prefix notation (also known as "Polish notation"): X+Y=+ X Y • Operators are written before their operands. The expressions given above are equivalent to / * A + B C D • As for Postfix, operators are evaluated left-to-right and brackets are superfluous. Operators act on the two nearest values on the right. I have again added (totally unnecessary) brackets to make this clear: • (/ (* A (+ B C) ) D)
  • 43. INFIX TO POSTFIX CONVERSION Algorithm 1) Scan the string from left to right 2) Make three columns symbol , postfix expression and stack 3) If symbol = = opening bracket push in stack (i.e put in stack column)
  • 44. INFIX TO POSTFIX CONVERSION 4) If symbol = = closing bracket pop all the elements from stack till we get opening bracket, pop the opening bracket also and then put the pop elements in the postfix expression column leaving opening bracket. 5) If symbol = = alphabet/ digit then put the symbol in postfix expression column 6) If symbol = = operator check priority of top element in the stack.
  • 45. INFIX TO POSTFIX CONVERSION If priority( top element)>= priority(symbol operator) then pop top element and put it in postfix expression column If priority( top element)< priority(symbol operator) then push the symbol in the stack 7) If all the symbol finished from the symbol pop all the elements from stack and put it in postfix expression column
  • 46. INFIX TO POSTFIX CONVERSION 3+4*5/6 Symbol Postfix Expression Stack Remark 3 3 Step 5 + 3 + Step 6 4 3 4 + Step 5 * 3 4 + * Step 6 5 3 4 5 + * Step 5 / 3 4 5 * + / Step 6 6 3 4 5 * 6 + / Step 5 0 3 4 5 * 6 / + Step 7
  • 47. A^B*C-D+E/F/(G+H) Symbol Postfix Expression Stack Remark A A Step 5 ^ ^ Step 6 B AB ^ Step 5 * AB^ * Step 6 C AB^C * Step 5 - AB^C* - Step 6 D AB^C*D - Step 5 + AB^C*D- + Step 6 E AB^C*D-E + Step 5 / AB^C*D-E +/ Step 6 F AB^C*D-EF +/ Step 5 / AB^C*D-EF/ +/ Step 6
  • 48. A^B*C-D+E/F/(G+H) Symbol Postfix Expression Stack Remark ( AB^C*D-EF/ +/( Step 3 G AB^C*D-EF/G +/( Step 5 + AB^C*D-EF/G +/(+ Step 6 H AB^C*D-EF/GH +/(+ Step 5 ) AB^C*D-EF/GH+ +/ Step 4 0 AB^C*D-EF/GH+/+ Step 7
  • 49. Infix to Postfix ( ( A + B ) — C * ( D / E ) ) + F
  • 50. Infix to Postfix • A* B+C,A+B*C,(A+B)*(C-D),A*B-C$D+E Symbol Postfix Expression Stack Remark A A * A * B AB * + AB* + C AB*C + 0 AB*C+
  • 51. INFIX TO PREFIX CONVERSION Algorithm 1) Scan the string from right to left 2) Make three columns symbol , prefix expression and stack 3) If symbol = = closing bracket push in stack (i.e put in stack column)
  • 52. INFIX TO PREFIX CONVERSION 4) If symbol = = opening bracket pop all the elements from stack till we get closing bracket, pop the closing bracket also and then put the pop elements in the postfix expression column leaving closing bracket. 5) If symbol = = alphabet/ digit then put the symbol in prefix expression column 6) If symbol = = operator check priority of top element in the stack. If priority( top element)> priority(symbol operator) then pop top element and put it in prefix expression column
  • 53. INFIX TO PREFIX CONVERSION If priority( top element)<= priority(symbol operator) then push the symbol in the stack 7) If all the symbol finished from the symbol pop all the elements from stack and put it in prefix expression column 8) Reverse the final string
  • 54. A+B*(C^(D-E)+F)-G Symbol Prefix Expression Stack Remark G G Step 5 - G - Step 6 ) G - ) Step 3 F GF - ) Step 5 + GF -)+ Step 6 ) GF -)+) Step 6 E GFE -)+) Step 5 - GFE -)+)- Step 6 D GFED -)+)- Step 5 ( GFED- -)+ Step 4 ^ GFED- -)+^ Step 6 C GFED-C -)+^ Step 5 ( GFED-C^+ - Step 4
  • 55. Symbol Prefix Expression Stack Remark * GFED-C^+ - * Step 6 B GFED-C^+B - * Step 5 + GFED-C^+B * - + Step 6 A GFED-C^+B * A - + Step 5 0 GFED-C^+B * A + - Step 7 Reverse the Prefix Expression:- The Result will be - +A * B + ^ C - DEFG
  • 56. A * B + C / D Symbol Prefix expression Stack Remark D D Step 5 / D / Step 6 C DC / Step 5 + DC/ + Step 6 B DC/B + Step 5 * DC/B + * Step 6 A DC/BA + * Step 5 0 DC/BA*+ +*AB/CD
  • 57. (A+B)*(C-D) Symbol Prefix expression Stack Remark ) ) D D ) - D )- C DC )- ( DC- * DC- * ) DC- *) B DC-B *) + DC-B *)+ A DC-BA *)+ ( DC-BA+* *+AB-CD
  • 58. 1. A*B+C 2. A+B*C 3. A*B-C$D+E 4. A+(B-C*D)-E/F$G
  • 60. Steps to convert Postfix to Infix Expression Step 1:- Scan the postfix expression from left to right. Step 2:- Initialize an empty string stack. Step 3:- If the scanned character is operand, push it into stack. Step 4:- Else if the scanned character is operator, pop two operands from stack, and add this Operator in between the two operands. namely, opd1 and opd2, and  push: (opd1 operator op2) into stack. Step 5:- Repeat steps from 3 to 4 until all the characters from the string are scanned. Step 6:-In the end, only one valid infix string will be present in the stack, pop it and return it.
  • 61. AB-DE+F*/ Symbol Stack Remark A A Step 3 B AB Step 3 - (A-B) Step 4 D (A-B)D Step 3 E (A-B)DE Step 3 + (A-B)(D+E) Step 4 F (A-B)(D+E)F Step 3 * (A-B)(D+E)*F Step 4 / (A-B)/((D+E)*F) Step 4
  • 62. ab+c* Symbol Stack Remark a a Step 3 b ab Step 3 + (a+b) Step 4 c (a+b) c Step 3 * ((a+b) * c) Step 4
  • 63. SIMULATING STACK USING RECURSION 1)A procedure is called recursive if the procedure is defined by itself. i.e. when a function is defined in terms of itself then it is called a recursive. 2) In the recursion, the procedure calls itself directly or indirectly. Directly means functions called itself repeatedly. Indirectly means a function calls the another function. Hence the functions are executed repeatedly, every time a new value is passed to the recursive function till the condition is satisfied. If the recursive procedure calls itself then current values of parameters must be saved, since they will be used again when a program is reactivated.
  • 64. RECURSION 3) Rules: There must be terminating condition to stop recursion. When function is called recursively the copy of the stack is maintain. E.g. Consider the definition of factorial of a positive integer n. fact(n)= 1 if(n==0) n*fact(n-1) otherwise
  • 65. RECURSION int fact(int n) { if(n==0) return 1; else return(n*fact(n)); }
  • 66. RECURSION • Function fact() is defined in terms of itself for n>0. • Value of the function at n=0 is 1 and it is called the base. Recursion terminates on reaching the base.
  • 67. * Removal of Recursion (using stack) Any recursive function can be converted to non recursive function through use of a stack. 1) A recursive call is similar to a call to another function. 2) Any call to a function requires that the function has storage area where it can store its local variables and actual parameters. 3) Return address must be saved before a call is made to a function. 4) Storage area for local variables, actual parameters and the return address can be provided through a stack. 5) In case of a recursive call, the value of local variables, parameters and the return address must be saved on the stack. 6) While returning from a nested call, the previous outer call must be recalled with resetting all the local variables and operation must resume from where it was suspended
  • 68. Rules for converting a recursive algorithm to non recursive one- • 1) Declare stack-: It will hold local variables, parameters, return address etc. 2) The first statement after the stack initialization must have a label • Steps required to replace a recursive call 1) Push all local variables and parameters into the stack 2) Push an integer i into stack i gives the return address. 3) Set the values of formal parameters 4) Transfer the control to the beginning of the function (i.e first label immediately after initialization of stack) 5) There should always be a label statement immediately following the recursive call This label is the return address
  • 69. Rules for converting a recursive algorithm to non recursive one- Steps required at the end of recursion function 1) If the stack is empty , then the recursion is finished 2) Otherwise pop the stack to restore the values of all local variables and parameters called by value 3) Pop the return address
  • 70. Back Tracking • It Can be used to solve NP-Complete problems such as 0-1 Knapsack more efficiently • Backtracking vs Dynamic Programming • Dynamic Programming – subsets of a solution are generated Backtracking – Technique for deciding that some subsets need not be generated • Efficient for many large instances of a problem (but not all)
  • 71. • Backtracking Technique • Solve problems in which a sequence of objects is chosen from a set Sequence satisfies some criterion • Modified DFS of a rooted tree Pre-order traversal • General-purpose algorithm does not specify order children visited – we will use left to right
  • 72. • N-Queen Problem • Goal: position n queens on a n x n board such that no two queens threaten each other • No two queens may be in the same row, column, or diagonal Sequence: n positions where queens are placed • Set: n2 positions on the board • Criterion: no two queens threaten each other
  • 73. • Place Q1 Q2 Q3 bracktrack,place Q2 1 2 3 4 1 Q 2 3 4 1,1 1 2 3 4 1 Q 2 X X Q 3 4 2,3 1,1 1 2 3 4 1 Q 2 Q 3 X X X X 4 1 2 3 4 1 Q 2 Q 3 4 2,3 1,1 2,4 1,1
  • 74. • Place Q3 Q4 BT,Q3,Q2,Q1 Q2 1 2 3 4 1 Q 2 Q 3 X Q 4 1 2 3 4 1 Q 2 Q 3 Q 4 X X X X 1 2 3 4 1 Q 2 3 4 1 2 3 4 1 Q 2 Q 3 4 2,4 1,2 1,2 3,2 2,4 1,1 3,2 2,4 1,1
  • 75. • Place Q3 Q4 1 2 3 4 1 Q 2 Q 3 Q 4 1 2 3 4 1 Q 2 Q 3 Q 4 X X Q 3,1 2,4 1,2 4,3 3,1 2,4 1,2