SlideShare a Scribd company logo
1 of 76
Download to read offline
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)
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
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

What's hot

stack and queue array implementation in java.
stack and queue array implementation in java.stack and queue array implementation in java.
stack and queue array implementation in java.CIIT Atd.
 
Stack Data Structure V1.0
Stack Data Structure V1.0Stack Data Structure V1.0
Stack Data Structure V1.0Zidny Nafan
 
Mcs011 solved assignment by divya singh
Mcs011 solved assignment by divya singhMcs011 solved assignment by divya singh
Mcs011 solved assignment by divya singhDIVYA SINGH
 
Queue implementation
Queue implementationQueue implementation
Queue implementationRajendran
 
Queue data structure
Queue data structureQueue data structure
Queue data structureMekk Mhmd
 
Algorithm: priority queue
Algorithm: priority queueAlgorithm: priority queue
Algorithm: priority queueTareq Hasan
 
Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListPTCL
 
Stack data structure
Stack data structureStack data structure
Stack data structureTech_MX
 
Data structures stacks
Data structures   stacksData structures   stacks
Data structures stacksmaamir farooq
 
Notes DATA STRUCTURE - queue
Notes DATA STRUCTURE - queueNotes DATA STRUCTURE - queue
Notes DATA STRUCTURE - queueFarhanum Aziera
 

What's hot (20)

stack and queue array implementation in java.
stack and queue array implementation in java.stack and queue array implementation in java.
stack and queue array implementation in java.
 
Stack
StackStack
Stack
 
Stack - Data Structure
Stack - Data StructureStack - Data Structure
Stack - Data Structure
 
Lecture 2d queues
Lecture 2d queuesLecture 2d queues
Lecture 2d queues
 
Stacks
StacksStacks
Stacks
 
Queues
Queues Queues
Queues
 
Stack Data Structure V1.0
Stack Data Structure V1.0Stack Data Structure V1.0
Stack Data Structure V1.0
 
Mcs011 solved assignment by divya singh
Mcs011 solved assignment by divya singhMcs011 solved assignment by divya singh
Mcs011 solved assignment by divya singh
 
Queue implementation
Queue implementationQueue implementation
Queue implementation
 
Stack
StackStack
Stack
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Algorithm: priority queue
Algorithm: priority queueAlgorithm: priority queue
Algorithm: priority queue
 
Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked List
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Data structures
Data structuresData structures
Data structures
 
Priority queues
Priority queuesPriority queues
Priority queues
 
Queue
QueueQueue
Queue
 
Queue by rajanikanth
Queue by rajanikanthQueue by rajanikanth
Queue by rajanikanth
 
Data structures stacks
Data structures   stacksData structures   stacks
Data structures stacks
 
Notes DATA STRUCTURE - queue
Notes DATA STRUCTURE - queueNotes DATA STRUCTURE - queue
Notes DATA STRUCTURE - queue
 

Similar to Chapter 4 stack

What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueWhat is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueBalwant Gorad
 
DS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxDS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxprakashvs7
 
Stack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTStack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTSoumen Santra
 
stack and queue array implementation, java.
stack and queue array implementation, java.stack and queue array implementation, java.
stack and queue array implementation, java.CIIT Atd.
 
Chapter 5 Stack and Queue.pdf
Chapter 5 Stack and Queue.pdfChapter 5 Stack and Queue.pdf
Chapter 5 Stack and Queue.pdfGirT2
 
Stack in Data Structure
Stack in Data StructureStack in Data Structure
Stack in Data StructureUshaP15
 
Chapter 5-stack.pptx
Chapter 5-stack.pptxChapter 5-stack.pptx
Chapter 5-stack.pptxHalid Assen
 
Stack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparationStack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparationRAtna29
 
Stack and its applications
Stack and its applicationsStack and its applications
Stack and its applicationsAhsan Mansiv
 
stack slide vghbjnkmfgvhbjnmkgvbhjnkmgbhjnkm
stack slide vghbjnkmfgvhbjnmkgvbhjnkmgbhjnkmstack slide vghbjnkmfgvhbjnmkgvbhjnkmgbhjnkm
stack slide vghbjnkmfgvhbjnmkgvbhjnkmgbhjnkmxadihe1593
 
Stack and Queue.pptx
Stack and Queue.pptxStack and Queue.pptx
Stack and Queue.pptxDdushb
 
Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxchandankumar364348
 
CD3291 2.5 stack.pptx
CD3291 2.5 stack.pptxCD3291 2.5 stack.pptx
CD3291 2.5 stack.pptxmareeswari15
 

Similar to Chapter 4 stack (20)

Stacks
StacksStacks
Stacks
 
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueWhat is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
 
DS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxDS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptx
 
Stack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTStack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADT
 
stack and queue array implementation, java.
stack and queue array implementation, java.stack and queue array implementation, java.
stack and queue array implementation, java.
 
Chapter 5 Stack and Queue.pdf
Chapter 5 Stack and Queue.pdfChapter 5 Stack and Queue.pdf
Chapter 5 Stack and Queue.pdf
 
Stack in Data Structure
Stack in Data StructureStack in Data Structure
Stack in Data Structure
 
notes.pdf
notes.pdfnotes.pdf
notes.pdf
 
Chapter 5-stack.pptx
Chapter 5-stack.pptxChapter 5-stack.pptx
Chapter 5-stack.pptx
 
Stack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparationStack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparation
 
5.-Stacks.pptx
5.-Stacks.pptx5.-Stacks.pptx
5.-Stacks.pptx
 
Stack and its applications
Stack and its applicationsStack and its applications
Stack and its applications
 
04 stacks
04 stacks04 stacks
04 stacks
 
Stack.pptx
Stack.pptxStack.pptx
Stack.pptx
 
stack slide vghbjnkmfgvhbjnmkgvbhjnkmgbhjnkm
stack slide vghbjnkmfgvhbjnmkgvbhjnkmgbhjnkmstack slide vghbjnkmfgvhbjnmkgvbhjnkmgbhjnkm
stack slide vghbjnkmfgvhbjnmkgvbhjnkmgbhjnkm
 
2.1 STACK & QUEUE ADTS
2.1 STACK & QUEUE ADTS2.1 STACK & QUEUE ADTS
2.1 STACK & QUEUE ADTS
 
Stack and Queue.pptx
Stack and Queue.pptxStack and Queue.pptx
Stack and Queue.pptx
 
Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
 
Unit 3 stack
Unit   3 stackUnit   3 stack
Unit 3 stack
 
CD3291 2.5 stack.pptx
CD3291 2.5 stack.pptxCD3291 2.5 stack.pptx
CD3291 2.5 stack.pptx
 

Recently uploaded

CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 

Recently uploaded (20)

CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 

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)
  • 42.
  • 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
  • 59.
  • 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