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");
}
}
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)
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.
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
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
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
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
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