You are on page 1of 9

Stacks P a g e | 2.

STACKS
Introduction  Static implementation of stack uses arrays to create a stack.
 In static implementation, the size of the stack has to be declared during
 Stack is a non-primitive linear data structure.
program design and after that it cannot be resized.
 This is an ordered list in which a data item is inserted and deleted from a
 Dynamic implementation is also referred to as linked list implementation
common end.
and uses pointers to work upon the stack.
 This common end is known as top of stack (TOS).
 As all the insertions and deletions in a stack take place from top of stack, Stack implementation using arrays
the last inserted element will be the first to be removed from the stack.
 That is why this is called as Last In First Out (LIFO) list. PUSH operation
 This is the process of inserting data items into the stack.
Stack terminology
 The variable top is used to store the position of the topmost element in the
Push stack.
 As the stack is empty initially, top is initialized to -1, i.e. a position out of
This is the process of insertion a data item into the stack.
the stack.
Pop Program : WAP to implement the PUSH operation using an array of five
Deleting a data item from the top of the stack is called pop operation. elements.
1. #include<stdio.h>
TOP 2. int stack[5]; /* Declaring a stack of 5 elements */
3. int top = -1; /* Initially top is out of the stack */
This term refers to the top of stack (TOS). The stack top is used to check
4. void push(); /* Function Prototype */
the position of the last value in the stack. 5. void main()
6. {
Stack underflow 7. push();
This is the situation when the stack is empty or contains no element. 8. }
9.
Hence, no more values can be popped out from the stack. 10. void push() /* Function Definition */
11. {
Stack overflow 12. int n;
This is the situation when the stack becomes full. Hence, no more 13. while(1)/* Infinite loop */
14. {
values can be pushed into the stack. 15. if(top==4)
16. { printf(“Stack overflow...”);
Implementation of stacks 17. break; }
18. printf(“Enter a value : “);
 Stack can be implemented in two ways –
19. scanf(“%d”, &n);
(a) Static implementation 20. top++;
21. stack[top] = n;
(b) Dynamic implementation 22. }
23. }
ACC, 103/9, Sec. – 10, Kumbha Marg, Pratap Nagar, Near SBBJ Bank, Sanganer, JAIPUR.
STACKS P a g e | 2.2

Algorithm to implement PUSH operation (using array) Algorithm to implement POP operation (using array)
Note : stack is an array of 5 integers Note : stack is an array of 5 integers
top stores the index of the topmost element in stack top stores the index of the topmost element in the stack
Step 1 : Set top = -1 Step 1 : Repeat Step 2 to Step 6 while (1)
Step 2 : Repeat Step 3 to Step 8 while (1) Step 2 : if (top = -1)
Step 3 : if (top = 4) Then go to Step 3
Then go to Step 4 Else go to Step 5
Else go to Step 6 Step 3 : Print “Stack Underflow….”
Step 4 : Print “Stack Overflow….” Step 4 : Go to Step 7
Step 5 : Go to Step 9 Step 5 : Print top[stack]
Step 6 : Input a value and store it in n Step 6 : Decrement top by 1
Step 7 : Increment top by 1 Step 7 : Stop
Step 8 : top[stack] = n
Step 9 : Stop Stack implementation using linked lists
 The logical structure of the node of a stack is similar to that of a singly
POP operation
linked list. it is given below –
 The process of processing values from the stack is called pop operation. struct node
 While popping a value from the stack, the element where top is pointing {
is extracted and the value of top is decremented by 1. int data;
struct node *next;
Program : Write a function to implement the POP operation.
};
1. void pop()
2. { PUSH operation
3. printf(“\n\n\nThe values in the stack are : \n”);
 The process of pushing a data item is almost similar to inserting a data
4. while (1)
item into a singly linked list.
5. {
 The only difference is that the top variable always stores the address of
6. if (top==-1)
the latest inserted node into the stack whereas in a singly linked list, head
7. {
8. printf(“\n\nStack underflow...”); always stores the address of the first node in the list.
9. break;  Dynamic implementation of stacks using a linked list is similar to a
10. } reverse singly linked list.
11. printf(“%d\t”, stack[top]);  This process is illustrated in the following figure –
12. top—; Top
PUSH 10 NULL 10
13. }
Top
14. } PUSH 20 NULL 10 20
Top
PUSH 30 NULL 10 20 30

ACC, 103/9, Sec. – 10, Kumbha Marg, Pratap Nagar, Sanganer, JAIPUR. Contact Nos. : 77370-08028, 98285-48028
STACKS P a g e | 2.3

Program : WAP to implement push operation using linked list Algorithm to implement PUSH operation (using Linked List)
representation. Note : top stores the address of the topmost element in the stack
1. #include<stdio.h> Step 1 : Set top = NULL
2. #include<conio.h>
Step 2 : Input a value in n
3. #include<stdlib.h>
Step 3 : Repeat Step 4 to Step 8 while (n != -1)
4. typedef struct node /* Definition of a node */
Step 4 : Create a node and store the address in temp
5. {
6. int data; Step 5 : data [temp] = n
7. struct node *next; Step 6 : next [temp] = top
8. }STACK; Step 7 : top = temp
9. Step 8 : Input a value in n
10. STACK* push(STACK *); /* Function prototype */ Step 9 : Stop
11. main()
12. { POP operation
13. STACK *top;  The procedure to pop a data item from a stack using linked list is shown
14. clrscr(); below –
15. top = NULL; /* Initially, there is no stack */ Top
16. top = push(top); NULL 10 20 30
17. } Top
18. POP 30 NULL 10 20
19. STACK* push(STACK *top) Top
20. { POP 20 NULL 10
21. STACK *temp; POP 10 Top = NULL (stack underflow)

22. int n;
23. printf(“Enter a value : “);
24. scanf(“%d”, &n); Program : Write a function to implement POP operation using linked list
25. while(n!=-1) /* Loop terminates when n = -1 */ representation.
26. { 1. STACK* pop(STACK *); /* Function prototype */
27. temp = (STACK *)malloc(sizeof(STACK)); 2.
28. temp->data = n; 3. STACK* pop(STACK *top)
29. temp -> next = top; 4. {
5. STACK *ptr;
30. top = temp;
6. while(1)
31. printf(“Enter a value : “); 7. {
32. scanf(“%d”, &n); 8. ptr = top;
33. } 9. if(top == NULL)
34. return top; 10. {
35. } 11. printf(“Stack Underflow...”);
12. return top;
13. }

ACC, 103/9, Sec. – 10, Kumbha Marg, Pratap Nagar, Sanganer, JAIPUR. Contact Nos. : 77370-08028, 98285-48028
STACKS P a g e | 2.4

14. printf(“%d\t”, top->data);  For example, let us consider an expression –


15. top = top->next; /* top moves to next element */
16. free(ptr); /* Delete the node pointed by ptr */ 12 + 9/3
17. } = 12 + 3 (‘/’ is evaluated first)
18. } = 15 (‘+’ evaluated after ‘/’)
Algorithm to implement POP operation (using Linked List) Types of notations
Note : top stores the address of the topmost element in the stack  There are three types of notations to represent an arithmetic expression –
Step 1 : Repeat Step 2 to Step 8 while (1)
Step 2 : ptr = top (a) Infix notation
Step 3 : if (top = NULL) (b) Prefix notation
Then go to Step 4 (c) Postfix notation
Else go to Step 6
Step 4 : Print “Stack Underflow” Infix notation
Step 5 : Go to Step 9
 The format of an infix expression is as follows –
Step 6 : Print data [top]
Step 7 : top = next [top] operand1 operator operator2
Step 8 : Release ptr  For example, A+B
Step 9 : Stop  The evaluation of infix expression primarily involves the precedence of
operators.
Evaluation of expression
 One must remember the correct precedence to evaluate an expression to
 In any language, mathematical or arithmetic expression must be handled get correct result.
properly.
 Stacks are primarily used to evaluate arithmetic expressions. An Prefix notation
expression is a valid logical combination of operators and operands.
 Jan Lukasiewich, the great mathematician from Poland, came with the new
 An arithmetic expression is evaluated on the basis of the precedence
technique for representing arithmetic expressions where operator will be
(priority) and associativity of the operators used in it.
placed before or after the operands.
 The precedence of various operators is given in the following table –
 This technique was called polish notation.
Precedence Operator  The main advantage of using these notations in computers is that we do
4 Parentheses () not have to remember the precedence while evaluating the expressions.
3 Exponentiation ( or ^)  Other advantage is that these notations do not use parenthesis while
2 *, /, % representing the expressions.
 Prefix notation is also known as polish notation. In this notation, the
1 +, -
operator is placed before both the operands.
 The operator with highest priority is evaluated first.
operator operand1 operand2
 When, in an expression, two operators have same precedence level then
the operator that comes first from left is evaluated first.  For example, an infix expression A + B will be represented in prefix
notation as +AB.
ACC, 103/9, Sec. – 10, Kumbha Marg, Pratap Nagar, Sanganer, JAIPUR. Contact Nos. : 77370-08028, 98285-48028
STACKS P a g e | 2.5

Postfix notation Converting infix expression into a postfix expression


 This representation is also known as reverse polish notation. The operator is  A stack is used to convert a given infix expression into equivalent postfix
placed after the operands. expression.
operand1 operand2 operator  An infix expression is provided as input in form of a string.
 For example, the infix expression A + B will be represented in postfix Example 1 : Convert the following infix expression into a postfix expression.
notation as AB+. A+B*C/D+E^F*G
Direct method of converting infix to prefix & postfix expression  Add symbol ‘#’ in the end of the given infix expression. Also push symbol
‘#’ into the operator stack. Now the infix expression looks like this –
Example 1 : A*B-C/D
A+B*C/D+E^F*G#
 * A B - C / D
 Now, we convert the infix expression into the postfix expression.
 A B * - / C D
 Scanned symbol Operator stack Postfix expression
 - * A B / C D (Prefix expression)
A # A
A*B-C/D + #+ A
 A B * - C / D B #+ AB
 A B * - C D / * #+* AB
 A B * C D / - (Postfix expression) C #+* ABC
/ #+/ ABC*
Example 2 : A*B+(C*D^E)+F/G*H
 A*B+(C*^DE)+F/G*H D #+/ ABC*D
 A*B+*C^DE+F/G*H + #+ ABC*D/+
 *AB+*C^DE+F/G*H E #+ ABC*D/+E
 *AB+*C^DE+/FG*H ^ #+^ ABC*D/+E
 *AB+*C^DE+*/FGH
F #+^ ABC*D/+EF
 +*AB*C^DE+*/FGH
* #+* ABC*D/+EF^
 + + * A B * C ^ D E * / F G H (Prefix expression)
G #+* ABC*D/+EF^G
A*B+(C*D^E)+F/G*H # # ABC*D/+EF^G*+
 A * B + ( C * D E ^ ) + F / G * H  So, the resultant postfix expression is -
  A * B + C D E ^ * + F / G * H ABC*D/+EF^G*+
  A B * + C D E ^ * + F / G * H
  A B * + C D E ^ * + F G / * H
  A B * + C D E ^ * + F G / H *
  AB*CDE^*++FG/H*
  A B * C D E ^ * + F G / H * + (Postfix expression)
ACC, 103/9, Sec. – 10, Kumbha Marg, Pratap Nagar, Sanganer, JAIPUR. Contact Nos. : 77370-08028, 98285-48028
STACKS P a g e | 2.6

Example 2 : Convert the following infix expression into a postfix expression. Algorithm to convert infix to postfix expression
A *( B +C^D) -E ^F* (G /H ) Step 1 : Input an infix expression
Solution : On adding symbol ‘#’ in the end of the given infix expression – Step 2 : Add symbol ‘#’ into the end of the infix expression
A*(B+C^D)-E^F*(G/H)# Step 3 : Push symbol ‘#’ into the operator stack.
Scanned symbol Operator stack Postfix expression Step 4 : Scan the symbol of infix expression one by one left to right.
A # A Step 5 : Repeat step 6 to step 10 while (scanned symbol ! = ‘#’)
* #* A Step 6 : if scanned symbol is operand then add to postfix expression.

( #*( A Step 7 : if symbol is ‘(‘ then add it to the operator stack.


Step 8 : (a) if symbol is operator then pop all the operators which have same
B #*( AB
or higher precedence then the scanned operator.
+ #*(+ AB (b) Add the popped operator to postfix expression.
C #*(+ ABC (c) Add the scanned symbol operator into operator stack.
^ #*(+^ ABC Step 9 : (a) if symbol is ‘)’ then pop all the operators from stack until left
D #*(+^ ABCD parenthesis ‘)’ encounters in operator stack.
(b) Remove left parenthesis ‘(’ from operator stack.
) #* ABCD^+
Step 10 : (a) if symbol is ‘#’ then pop all the operators from the stack
- #- ABCD^+*
(b) Add the popped operators to postfix expression except ‘#’
E #- ABCD^+*E
Step 11 : Stop
^ #-^ ABCD^+*E
Algorithm for evaluating a postfix expression
F #-^ ABCD^+*EF
Step 1 : Input the postfix expression to be calculated.
* #-* ABCD^+*EF^
Step 2 : Add the symbol ‘#’ at the end of postfix expression
( #-*( ABCD^+*EF^
Step 3 : Scan characters from the postfix expression one by one left to right.
G #-*( ABCD^+*EF^G
Step 4 : If the scanned symbol is operand then push it into the stack.
/ #-*(/ ABCD^+*EF^G
Step 5 : If the scanned symbol is operator then pop last two elements of stack
H #-*(/ ABCD^+*EF^GH
and evaluate them as - [top-1] operator [top]
) #-* ABCD^+*EF^GH/
Step 6 : After evaluation, push the result into the stack
# # ABCD^+*EF^GH/*-
Step 7 : Repeat Step 3 to Step 6 until ‘#’ is scanned.
The resultant postfix expression is –
Step 8 : Pop the element of stack which will be the value of evaluation of the
ABCD^+*EF^GH/*- postfix expression.
Step 9 : Stop
ACC, 103/9, Sec. – 10, Kumbha Marg, Pratap Nagar, Sanganer, JAIPUR. Contact Nos. : 77370-08028, 98285-48028
STACKS P a g e | 2.7

Example : Evaluate the following postfix expression — Scanned Operand stack Calculation
ABC*D/+EF^G *+ Symbol
The values are— A A
A = 3, B = 5, C = 2, D = 2, E = 3, F = 2, G = 3 B A, B
Solution : Appending ‘#’ in the end of the postfix expression – C A, B, C
ABC*D/+EF^G*+# * A, (B*C) B*C
Scanned Symbol Operand stack Calculation D A, (B*C), D
A 3,
/ A, ((B*C))/D) (B*C)/D
B 3, 5 + (A+((B*C))/D)) A+((B*C)/D)
C 3, 5, 2 E (A+((B*C))/D)), E
* 3, 10 5*2=10 F (A+((B*C))/D)), E, F

D 3, 10, 2 ^ (A+((B*C))/D)), (E^F) E^F


G (A+((B*C))/D)), (E^F), G
/ 3, 5 10/2=5
* (A+((B*C))/D)), ((E^F)*G) (E^F)*G
+ 8
+ ((A+((B*C))/D)),((E^F)*G)) (A+((B*C)/D))+((E^F)*G)
E 8, 3
# (A+((B*C)/D))+((E^F)*G)
F 8, 3, 2
 We get the infix expression after removing all the unnecessary brackets
^ 8, 9 3^2=9 from the last expression.
G 8, 9, 3
A+B*C/D+E^F*G (Infix expression)
* 8, 27 9*3 =27
+ 35 8+27 =35
Recursion
#  Recursion is termed as a very powerful tool in the world of programming.
Ans. = 35  This is a very short substitute for relatively long and complicated
problems.
Converting a postfix expression into an infix expression  In recursion technique, a function calls itself. It is used to solve problems
 If, while evaluating a postfix expression, the values of A, B, C, ……… are involving loops, in reverse order.
not mentioned then the process of evaluating a postfix expression will  It is also an alternative to iteration in making a function execute
convert a given postfix expression into an infix expression. repeatedly.
Example : Convert the following postfix expression into an infix expression.  Recursion is of two types – direct and indirect recursion.
 In direct recursion, a function calls itself multiple times repetitively.
ABC*D/+EF^G*+
 In indirect recursion, a function calls some other function and the called
Solution : Appending ‘#’ in the postfix expression –
function keep invoking the calling function.
ABC*D/+EF^G*+ #
ACC, 103/9, Sec. – 10, Kumbha Marg, Pratap Nagar, Sanganer, JAIPUR. Contact Nos. : 77370-08028, 98285-48028
STACKS P a g e | 2.8

 We need to keep some important facts in mind while working with Program : WAP to print the reverse of an integer number entered by user.
recursion. They are – 1. #include<stdio.h>
o There must be a terminating condition in a recursive function. This 2. #include<conio.h>
3. long int reverse(int);
condition is also known as base case. Base case is a case in which the
4. main()
function does not call itself. 5. {
o In absence of a base case, the function keep on calling itself until the 6. int n;
space in the memory is not fully occupied. 7. long int result;
8. clrscr();
o Every time a new recursive call is made, a new memory space is
9. printf(“Enter the number : “);
allocated to each automatic variable used by the recursive routine. 10. scanf(“%d”, &n);
o A recursive function executes in the reverse order. This means a stack is 11. result = reverse(n);
always used to store values from each calling of the recursive function. 12. printf(“After reversing : %ld”, result);
13. getch();
o Each time recursive call is there, the duplicated values of the local 14. }
variables of a recursive call are pushed onto the stack and all these 15.
values are available to the respective function call when it is popped 16. long int reverse(int num)
out from the stack. 17. {
18. int rem;
Program : WAP to calculate the factorial of given number entered by the 19. static long int sum=0;
user. 20. if(num==0)
21. return(num);
1. #include<stdio.h>
22. else
2. #include<conio.h>
23. {
3. long fact(int);
24. rem = num%10;
4. main()
25. sum = sum * 10 + rem;
5. { 26. reverse(num/10);
6. int n; 27. }
7. long result; 28. return(sum);
8. clrscr(); 29. }
9. printf(“Enter a number : “);
10. scanf(“%d”, &n); Program : WAP to ask a number and calculate the power for that number.
11. result = fact(n); 1. #include<stdio.h>
12. printf(“The factorial of %d is %ld”, n, result); 2. #include<conio.h>
13. getch(); 3. long int power(int, int);
14. } 4. main()
15. long fact(int num) 5. {
16. { 6. int n, p;
17. if(num==1) 7. long int result;
18. return(num); 8. clrscr();
19. else 9. printf(“Enter the number : “);
20. return(num*fact(num-1)); 10. scanf(“%d”, &n);
21. } 11. printf(“Enter the power : “);
12. scanf(“%d”, &p);

ACC, 103/9, Sec. – 10, Kumbha Marg, Pratap Nagar, Sanganer, JAIPUR. Contact Nos. : 77370-08028, 98285-48028
STACKS P a g e | 2.9

13. result = power(n, p); TOWER OF HANOI


14. printf(“%d raised to power %d = %ld”, n, p,result);
15. getch();  The problem of Tower of Hanoi is to move the disk from one peg to
16. } another with the use of a temporary peg. Let us assume that these pegs are
17. long int power(int num, int pow) Source and Dest. We want to move the disks from Source to Dest with the
18. {
help of Temp peg. The conditions for this game are –
19. int rem;
20. static long int sum=0;  We can move only one disk from one peg to another at a time.
21. if(pow==0)  Larger disk cannot be placed on a smaller disk.
22. return(1);
 Assuming that initially all the disks are stacked on the Source peg.
23. else
24. return(num * power(num, pow-1)); Transferring all the disks from Source to Dest can recursively defined as
25. } follows :
Program : WAP to print n terms of the Fibonacci series – o Move the top (n-1) disks from Source to Temp peg.
o Move the nth disk to Dest peg.
0, 1, 1, 2, 3, 5, . . . . . . . . .
o Move the (n-1) disks stacked on Temp peg to Source peg.
1. #include<stdio.h>
2. #include<conio.h>
3. 1. #include<stdio.h>
4. void fibo(int, int, int, int);
2. main()
5. main()
6. { 3. {
7. int t1, t2, n, c; 4. char source=‘S’, temp=‘T’, dest=‘D’;
8. clrscr(); 5. int ndisk;
9. printf(“Enter the no. of terms to be printed : “); 6. printf(“Enter the number of disks : ”);
10. scanf(“%d”, &n);
7. scanf(“%d”, &ndisk);
11. t1 = 0;
12. t2 = 1; 8. printf(“The sequence is :\n”);
13. printf(“%d\t%d”, t1, t2); /* Printing first two terms */ 9. hanoi(ndisk, source, temp, dest);
14. c = 2; /* 2 terms already printed */ 10. }
15. fibo(t1, t2, c, n); /* Function call */ 11.
16. getch(); 12. void hanoi(int ndisk, char source, char temp, char dest)
17. }
13. {
18.
19. void fibo(int t1, int t2, int count, int n) 14. if(ndisk>0)
20. { 15. {
21. int t3; 16. hanoi(ndisk-1, source, dest, temp);
22. if(count==n) 17. printf(“Move disk %d from %c to %c”, ndisk, source, dest);
23. return;
18. hanoi(ndisk-1, temp, source, dest);
24. t3 = t1 + t2;
25. count++; 19. }
26. printf(“\t%d\t”, t3); 20. }
27. fibo(t2, t3, count, n); /* Recursive function call */
28. }

ACC, 103/9, Sec. – 10, Kumbha Marg, Pratap Nagar, Sanganer, JAIPUR. Contact Nos. : 77370-08028, 98285-48028

You might also like