2.1 Operations Performed on Stack 2.2 Stack Implementation 2.3 Stack Using Arrays 2.4 Applications of Stacks 2.5 Converting Infix to Postfix Expression 2.6 Evaluating Postfix Expression The Stack 1
 A stack is one of the most important and useful non- primitive linear data structure in computer science.  It is an ordered collection of items into which new data items may be added/inserted and from which items may be deleted at only one end, called the top of the stack.  As all the addition and deletion in a stack is done from the top of the stack, the last added element will be first removed from the stack. That is why the stack is also called Last-in-First-out (LIFO).  Note that the most frequently accessible element in the stack is the top most elements, whereas the least accessible element is the bottom of the stack. Definition 2
Stack Operations 3 Top Stack is empty. Top Add(20) Top Add(33) Top Add(47) Top Delete(47) Top Add(77) Top Delete(77) Top Delete(33) Figure 3.1 Stack operations.
 The insertion (or addition) operation is referred to as push, and the deletion (or remove) operation as pop.  A stack is said to be empty or underflow, if the stack contains no elements. At this point the top of the stack is present at the bottom of the stack.  And it is overflow when the stack becomes full, i.e., no other elements can be pushed onto the stack. At this point the top pointer is at the highest location of the stack. Stack Operations 4
 The primitive operations performed on the stack are as follows:  PUSH: The process of adding (or inserting) a new element to the top of the stack is called PUSH operation. Pushing an element to a stack will add the new element at the top. After every push operation the top is incremented by one. If the array is full and no new element can be accommodated, then the stack overflow condition occurs.  POP: The process of deleting (or removing) an element from the top of stack is called POP operation. After every pop operation the stack is decremented by one. If there is no element in the stack and the pop operation is performed then the stack underflow condition occurs. 2.1 Operations Performed on Stack 5
 Stack can be implemented in two ways: 1. Static implementation (using arrays) — sequential stack 2. Dynamic implementation (using pointers) — linked stack  Static implementation uses arrays to create stack.  a very simple technique but is not a flexible way, the size cannot be varied  static implementation is not an efficient method when resource optimization is concerned (i.e., memory utilization). 2.2 Stack Implementation 6
 For example a stack is implemented with array size 50. That is before the stack operation begins, memory is allocated for the array of size 50. Now if there are only few elements (say 30) to be stored in the stack, then rest of the statically allocated memory (in this case 20) will be wasted, on the other hand if there are more number of elements to be stored in the stack (say 60) then we cannot change the size array to increase its capacity.  The above said limitations can be overcome by dynamically implementing (is also called linked list representation) the stack using pointers. Example 7
 Suppose STACK[SIZE] is a one dimensional array for implementing the stack, which will hold the data items. TOP is the pointer that points to the top most element of the stack.  Let DATA is the data item to be pushed.  Algorithm for push 1. If TOP = SIZE – 1, then: (a) Display “The stack is in overflow condition” (b) Exit 2. TOP = TOP + 1 3. STACK [TOP] = ITEM 4. Exit 2.3 Stack Using Arrays-Algorithm for push 8
 DATA is the popped (or deleted) data item from the top of the stack.  Algorithm for pop 1. If TOP < 0, then (a) Display “The Stack is empty” (b) Exit 2. Else remove the Top most element 3. DATA = STACK[TOP] 4. TOP = TOP – 1 5. Exit Stack Using Arrays-Algorithm for pop 9
insert(int item) { if (top>=n-1) { printf(“Stack Full”); return; }; top=top+1; s[top]=item; return; } Push and Pop - Insert and Delete 10 dele( ) { if (top<0) { printf(“Stack Empty”); return; } item=s[top]; printf(“Deleted item is %d”, item); top=top-1; return; }
//This program is to demonstrate the operations performed //on the stack and it is implementation using arrays #include<stdio.h> #include<stdlib.h> #include<conio.h> //Defining the maximum size of the stack #define MAXSIZE 100 //Declaring the stack array and top variables in a structure struct stack { int stack[MAXSIZE]; int Top; }; typedef struct stack NODE; Stack Operations-C Program(1) 11
//This function will add/insert an element to Top of the stack void push(NODE *pu) { int item; if (pu->Top == MAXSIZE-1) { printf("nThe Stack Is Full."); } else { printf("nEnter The Element To Be Inserted = "); scanf("%d", &item); pu->stack[++pu->Top]=item; } } Stack Operations-C Program(2) 12
//This function will delete an element from the Top of the stack void pop(NODE *po) { int item; if (po->Top == -1) printf("nThe Stack Is Empty."); else { item=po->stack[po->Top--]; printf("nThe Deleted Element Is = %d", item); } } Stack Operations-C Program(3) 13
//This function to print all the existing elements in the stack void traverse(NODE *pt) { int i; if (pt->Top == -1) printf("nThe Stack is Empty"); else { printf("nnThe Element(s) In The Stack(s) is/are..."); for(i=pt->Top; i>=0; i--) printf ("n %d", pt->stack[i]); } } Stack Operations-C Program(4) 14
int main( ) { int choice; char ch; NODE ps; ps.Top=-1; do { system("cls"); printf("n1. PUSH"); //A menu for the stack operations printf("n2. POP"); printf("n3. TRAVERSE"); printf("nEnter Your Choice = "); scanf ("%d", &choice); Stack Operations-C Program(5) 15
switch(choice) { case 1: //Calling push() function by passing the structure pointer to the function push(&ps); break; case 2: //calling pop() function pop(&ps); break; case 3: //calling traverse() function traverse(&ps); break; default: printf("nYou Entered Wrong Choice"); } Stack Operations-C Program(6) 16
printf("nnPress (Y/y) To Continue = "); //Removing all characters in the input buffer //for fresh input(s), especially <<Enter>> key fflush(stdin); scanf("%c", &ch); } while(ch == 'Y' || ch == 'y'); } Stack Operations-C Program(7) 17
 Applications of stacks  Stack is internally used by compiler when any recursive function is executed  If we want to implement a recursive function non- recursively, stack is programmed explicitly.  Stack is also used to evaluate a mathematical expression and to check the parentheses in an expression. 2.4 Applications of Stacks 18
 Recursion occurs when a function is called by itself repeatedly, the function is called recursive function. The general algorithm model for any recursive function contains the following steps: 1. Prologue: Save the parameters, local variables, and return address. 2. Body: If the base criterion has been reached, then perform the final computation and go to step 3; otherwise, perform the partial computation and go to step 1 (initiate a recursive call). 3. Epilogue: Restore the most recently saved parameters, local variables, and return address. Applications of Stacks- Recursion 19
Figure 3.2 Flowchart model for a recursive algorithm Flowchart model for a recursive algorithm 20
 The Last-in-First-Out characteristics of a recursive function points that the stack is the most obvious data structure to implement the recursive function.  As a function calls a (may be or may not be another) function, its arguments, return address and local variables are pushed onto the stack. Since each function runs in its own environment or context, it becomes possible for a function to call itself — a technique known as recursion. This capability is extremely useful and extensively used — because many problems are elegantly specified or solved in a recursive way. Stack and Recursion 21
// Program to find factorial of a number, recursively #include<conio.h> #include<iostream> using namespace std; void fact(int no, int facto) { if (no <= 1) { // Final computation cout<<"nThe Factorial is = "<<facto; return; } else { // Partial computation of the program facto=facto*no; fact(--no, facto); // Function call to itself, that is recursion } } Calculating Factorial of n Recursively 22
int main() { system("cls"); int number, factorial; // Initialization of formal parameters, local variables and etc. factorial=1; cout<<"nEnter the No = "; cin>>number; fact(number, factorial); //Starting point of the function, which calls itself getch(); } Calculating Factorial of n Recursively 23
 Recursion of course is an elegant programming technique, but not the best way to solve a problem, even if it is recursive in nature. This is due to the following reasons: 1. It requires stack implementation. 2. It makes inefficient utilization of memory, as every time a new recursive call is made a new set of local variables is allocated to function. 3. Moreover it also slows down execution speed, as function calls require jumps, and saving the current state of program onto stack before jump. Recursion vs Iteration 24
Recursion vs Iteration (Cont.) 25 No. Iteration Recursion 1 It is a process of executing a statement or a set of statements repeatedly, until some specified condition is specified. Recursion is the technique of defining anything in terms of itself. 2 Iteration involves four clear-cut steps like initialization, condition, execution, and updating. There must be an exclusive if statement inside the recursive function, specifying stopping condition. 3 Any recursive problem can be solved iteratively. Not all problems have recursive solution. 4 Iterative counterpart of a problem is more efficient in terms of memory utilization and execution speed. Recursion is generally a worse option to go for simple problems, or problems not recursive in nature.
1. It consumes more storage space because the recursive calls along with automatic variables are stored on the stack. 2. The computer may run out of memory if the recursive calls are not checked. 3. It is not more efficient in terms of speed and execution time. 4. According to some computer professionals, recursion does not offer any concrete advantage over non-recursive procedures/functions. 5. If proper precautions are not taken, recursion may result in non-terminating iterations. 6. Recursion is not advocated when the problem can be through iteration. Recursion may be treated as a software tool to be applied carefully and selectively. Disadvantages of Recursion 26
 So far we have discussed the comparative definition and disadvantages of recursion with examples. Now let us look at the Tower of Hanoi problem and see how we can use recursive technique to produce a logical and elegant solution. Tower of Hanoi Problem 27
 three pegs (or towers) X, Y and Z (or A, B and C) exist. There will be n different sized disks. Each disk has a hole in the center so that it can be stacked on any of the pegs. At the beginning, the disks are stacked on the X peg, that is the largest sized disk on the bottom and the smallest sized disk on top.  the rules to be followed during transfer: 1. Transferring the disks from the source peg to the destination peg such that at any point of transformation no large size disk is placed on the smaller one. 2. Only one disk may be moved at a time. 3. Each disk must be stacked on any one of the pegs. Tower of Hanoi Problem 28
 Origins The puzzle was invented by the French mathematician Édouard Lucas in 1883. There is a story about an Indian temple in Kashi Vishwanath which contains a large room with three time-worn posts in it surrounded by 64 golden disks. Brahmin priests, acting out the command of an ancient prophecy, have been moving these disks, in accordance with the immutable rules of the Brahma, since that time. The puzzle is therefore also known as the Tower of Brahma puzzle. According to the legend, when the last move of the puzzle will be completed, the world will end. It is not clear whether Lucas invented this legend or was inspired by it. From http://en.wikipedia.org/wiki/Tower_of_Hanoi Tower of Hanoi Problem 29
Tower of Hanoi Problem 30
The Towers of Hanoi: Solution for Two Disks 31
The Towers of Hanoi: Solution for Three Disks 32
The Towers of Hanoi: Solution for Five Disks
#include<stdio.h> int hanoi(int n, char one, char two, char three) { if(n==1) printf("%c --> %cn", one, three); else { hanoi(n-1, one, three, two); printf("%c --> %cn", one, three); hanoi(n-1, two, one, three); } } The Towers of Hanoi-C Program 34 int main() { int n; while(scanf("%d", &n)!=EOF) hanoi(n, 'a', 'b', 'c'); }
 Another application of stack is calculation of postfix expression. There are basically three types of notation for an expression (mathematical expression, An expression is defined as the number of operands or data items combined with several operators.) 1. Infix notation 2. Prefix notation 3. Postfix notation  The infix notation is what we come across in our general mathematics, where the operator is written in- between the operands. For example : The expression to add two numbers A and B is written in infix notation as: A + B Expression 35
 The prefix notation is a notation in which the operator(s) is written before the operands, it is also called polish notation in the honor of the polish mathematician Jan Lukasiewicz who developed this notation. The same expression when written in prefix notation looks like: + A B  In the postfix notation the operator(s) are written after the operands, so it is called the postfix notation (post means after), it is also known as suffix notation or reverse polish notation. The above expression if written in postfix expression looks like: A B + Expression 36
 The prefix and postfix notations are not really as awkward to use as they might look. For example, a C function to return the sum of two variables A and B (passed as argument) is called or invoked by the instruction: add(A, B)  Note that the operator add (name of the function) precedes the operands A and B.  Because the postfix notation is most suitable for a computer to calculate any expression (due to its reverse characteristic), and is the universally accepted notation for designing Arithmetic and Logical Unit (ALU) of the CPU (processor). Expression 37
 Human beings are quite used to work with mathematical expressions in infix notation, which is rather complex. One has to remember a set of rules while using this notation and it must be applied to expressions in order to determine the final value. These rules include precedence, BODMAS, and associativity.  In a postfix expression operands appear before the operator, so there is no need for operator precedence and other rules.  BODMAS: short for “Brackets ,Division,Multiplication, Addition,Subtraction” Advantages of using postfix notation 38
 The method of converting infix expression A + B * C to postfix form is: A + B * C Infix Form A + (B * C) Parenthesized expression A + (B C *) Convert the multiplication A (B C *) + Convert the addition A B C * + Postfix form 2.5 Converting Infix To Postfix Expression 39
 The rules to be remembered during infix to postfix conversion are: 1. Parenthesize the expression starting from left to right. 2. During parenthesizing the expression, the operands associated with operator having higher precedence are first parenthesized. For example in the above expression B*C is parenthesized first before A+B. 3. The sub-expression (part of expression), which has been converted into postfix, is to be treated as single operand. 4. Once the expression is converted to postfix form, remove the parenthesis. The Rule of Converting Infix to Postfix Expression 40
 Example 1: Give postfix form for A + [ (B + C) + (D + E) * F ] / G  Solution: Evaluation order is A + { [ (BC +) + (DE +) * F ] / G } A + { [ (BC +) + (DE + F *) ] / G } A + [ (BC + DE + F * +) / G ] A + ( BC + DE + F *+ G / ) Postfix Form: ABC + DE + F * + G / + Example 1 41
 Example 2: Give postfix form for (A + B) * C / D + E ^ A / B  Solution: Evaluation order is [(AB +) * C / D ] + [ (EA ^) / B ] [(AB +) C * / D ] + [ (EA ^) B / ] [(AB +) C * D / ] + [ (EA ^) B / ] (AB +) C * D / (EA ^) B / + Postfix Form: AB + C * D / EA ^ B / + Example 2 42
 Algorithm  Suppose P is an arithmetic expression written in infix notation. This algorithm finds the equivalent postfix expression Q.  Besides operands and operators, P (infix notation) may also contain left and right parentheses.  Assume that the operators in P consists of only exponential ( ^ ), multiplication ( * ), division ( / ), addition ( + ) and subtraction ( - ).  Use a stack to temporarily hold the operators and left parentheses.  The postfix expression Q will be constructed from left to right using the operands from P and operators, which are removed from stack.  Begin by pushing a left parenthesis onto stack and adding a right parenthesis at the end of P. the algorithm is completed when the stack is empty. Algorithm 43
1. Push “(” onto stack, and add“)” to the end of P. 2. Scan P from left to right and repeat steps 3 to 6 for each element of P until the stack is empty. 3. If an operand is encountered, add it to Q. 4. If a left parenthesis is encountered, push it onto stack. 5. If an operator is encountered, then: ⊗ (a) Repeatedly pop from stack and add Q each operator (on the top of stack), which has the same precedence as, or higher precedence than . ⊗ (b) Add to stack. ⊗ 6. If a right parenthesis is encountered, then: (a) Repeatedly pop from stack and add to Q (on the top of stack until a left parenthesis is encountered. (b) Remove the left parenthesis. [Do not add the left parenthesis to P.] 7. Exit. Note. is used to symbolize any operator in P. ⊗ Algorithm 44
 infix expression: P = A + ( B / C - ( D * E ^ F ) + G ) * H Algorithm 45 Character scanned Stack Postfix Expression Q A + ( B / C – ( D * E ^ F ) + G ) * H ) ( ( + ( + ( ( + ( ( + ( / ( + ( / ( + ( - ( + ( - ( ( + ( - ( ( + ( - ( * ( + ( - ( * ( + ( - ( * ^ ( + ( - ( * ^ ( + ( - ( + ( + ( + ( + ( + ( + * ( + * A A A A B A B A B C A B C / A B C / A B C / D A B C / D A B C / D E A B C / D E A B C / D E F A B C / D E F ^ * A B C / D E F ^ * - A B C / D E F ^ * - G A B C / D E F ^ * - G + A B C / D E F ^ * - G + A B C / D E F ^ * - G + H A B C / D E F ^ * - G + H * +
// This program is to convert the infix to postfix expression #include<stdio.h> #include<stdlib.h> #include<conio.h> #include<string.h> // Defining the maximum size of the stack #define MAXSIZE 100 // Declaring the stack array and top variables in a structure struct stack { char stack[MAXSIZE]; int Top; }; // type definition allows the user to define an identifier that would // represent an existing data type. The user-defined data type identifier // can later be used to declare variables. typedef struct stack NODE; Infix to Postfix Expression-C Program(1) 46
// This function will add/insert an element to Top of the stack void push(NODE *pu, char item) { if (pu->Top == MAXSIZE-1) { printf("nThe stack is full"); getch(); } else pu->stack[++pu->Top]=item; } // This function will delete an element from the Top of the stack char pop(NODE *po) { char item; if(po->Top == -1) { printf("nThe stack is empty. Invalid infix expression"); exit(0); } else { item=po->stack[po->Top--]; return(item); } } Infix to Postfix Expression-C Program(2) 47
// This function returns the precedence of the operator int prec(char symbol) { switch(symbol) { case '(': return(1); case ')': return(2); case '+': case '-': return(3); case '*': case '/': case '%': return(4); case '^': return(5); default: return(0); } } Infix to Postfix Expression-C Program(3) 48
// This function will return the postfix expression of an infix void Infix_Postfix(char infix[], char postfix[]) { int i,j,len; char ch; NODE ps; ps.Top=-1; len=strlen(infix); infix[len++]=')'; // At the end of the string inputting a parenthesis ')' push(&ps,'('); // Parenthesis is pushed to the stack for(int i=0,j=0;i<len;i++) { switch(prec(infix[i])) { case 1: // Scanned char is '(' push to the stack push(&ps,infix[i]); break; Infix to Postfix Expression-C Program(4) 49
case 2: // Scanned char is ')' pop the operator(s) and add to the postfix expression ch=pop(&ps); while(ch != '(') { postfix[j++]=ch; ch=pop(&ps); } break; // Scanned operator is +,– then pop the higher or same // precedence operator to add postfix before pushing // the scanned operator to the stack case 3: ch=pop(&ps); while(prec(ch) >= 3) { postfix[j++]=ch; ch=pop(&ps); } push(&ps,ch); push(&ps,infix[i]); break; Infix to Postfix Expression-C Program(5) 50
// Scanned operator is *,/,% then pop the higher or // same precedence operator to add postfix before // pushing the scanned operator to the stack case 4: ch=pop(&ps); while(prec(ch) >= 4) { postfix[j++]=ch; ch=pop(&ps); } push(&ps,ch); push(&ps,infix[i]); break; Infix to Postfix Expression-C Program(6) 51
// Scanned operator is ^ then pop the same // precedence operator to add to postfix before pushing // the scanned operator to the stack case 5: ch=pop(&ps); while(prec(ch) == 5) { postfix[j++]=ch; ch=pop(&ps); } push(&ps,ch); push(&ps,infix[i]); break; Infix to Postfix Expression-C Program(7) 52
//Scanned char is a operand simply add to the postfix expression default: postfix[j++]=infix[i]; } } printf("nThe postfix expression is = "); puts(postfix); // Printing the postfix notation to the screen } Infix to Postfix Expression-C Program(8) 53
int main() { char choice, infix[MAXSIZE],postfix[MAXSIZE]; do { system("cls"); printf("nEnter the infix expression = "); fflush(stdin); gets(infix); // Inputting the infix notation Infix_Postfix(infix, postfix); // Calling the infix to postfix function printf("nDo you want to continue (Y/y) = "); fflush(stdin); scanf("%c", &choice); } while(choice == 'Y' || choice == 'y'); } Infix to Postfix Expression-C Program(9) 54
 Following algorithm finds the RESULT of an arithmetic expression P written in postfix notation. The algorithm evaluates P by using a STACK to hold operands.  Algorithm: 1. Add a right parenthesis “)” at the end of P. [sentinel.] 2. Scan P from left to right and repeat Steps 3 and 4 for each element of P until the sentinel “)” is encountered. 3. If an operand is encountered, put it on STACK. 4. If an operator is encountered, then: ⊗ (a) Remove the two top elements of STACK, where A is the top element and B is the next-to-top element. (b) Evaluate B A. ⊗ (c) Place the result on to the STACK. 5. Result equal to the top element on STACK. 6. Exit. 2.6 Evaluating Postfix Expression 55
 P= 2 3 4 * + 9 3 / - example
// This program is to evaluate postfix expression. // The stack is used and it is implemented using arrays. #include<stdio.h> #include<stdlib.h> #include<math.h> #include<conio.h> #include<string.h> // Defining the maximum size of the stack #define MAXSIZE 100 // Declaring the stack array and top variables in a structure struct stack { int stack[MAXSIZE]; int Top; }; Evaluating Postfix Expression -C Program(1) 57
// type definition allows the user to define an identifier that would // represent an existing data type. The user-defined data type identifier // can later be used to declare variables. typedef struct stack NODE; // This function will add/insert an element to Top of the stack void push(NODE *pu,int item) { if (pu->Top == MAXSIZE-1) { printf("nThe stack is full"); getch(); } else pu->stack[++pu->Top]=item; } Evaluating Postfix Expression -C Program(2) 58
// This function will delete an element from the Top of the stack int pop(NODE *po) { int item; if (po->Top==-1) printf("nThe Stack Is Empty. Invalid Infix expression"); else item=po->stack[po->Top--]; return(item); } Evaluating Postfix Expression -C Program(3) 59
// This function will return the postfix expression of an infix int Postfix_Eval(char postfix[]) { int a,b,temp,len; NODE ps; // Declaring an pointer variable to the structure ps.Top=-1; // Initializing the Top pointer to NULL len=strlen(postfix); // Finding length of the string for(int i=0;i<len;i++) { if(postfix[i]<='9' && postfix[i]>='0') push(&ps,(postfix[i]-48)); // Operand is pushed on the stack else { a=pop(&ps); b=pop(&ps);// Pop the top most two operand for operation Evaluating Postfix Expression -C Program(4) 60
switch(postfix[i]) { case '+': temp=b+a; break; case '-': temp=b-a;break; case '*': temp=b*a;break; case '/': temp=b/a;break; case '%': temp=b%a;break; case '^': temp=pow(b,a); }/*End of switch */ push(&ps,temp); } } return(pop(&ps)); } Evaluating Postfix Expression -C Program(5) 61
int main() { char choice, postfix[MAXSIZE]; do { system("cls"); printf("nnEnter the Postfix expression="); fflush(stdin); gets(postfix); // Inputting the postfix notation printf("nnThe postfix evaluation is = %d", Postfix_Eval(postfix)); printf("nnDo you want to continue (Y/y) ="); fflush(stdin); scanf("%c", &choice); } while(choice=='Y'||choice=='y'); } Evaluating Postfix Expression -C Program(6) 62

The Stack in data structures .ppt

  • 1.
    2.1 Operations Performedon Stack 2.2 Stack Implementation 2.3 Stack Using Arrays 2.4 Applications of Stacks 2.5 Converting Infix to Postfix Expression 2.6 Evaluating Postfix Expression The Stack 1
  • 2.
     A stackis one of the most important and useful non- primitive linear data structure in computer science.  It is an ordered collection of items into which new data items may be added/inserted and from which items may be deleted at only one end, called the top of the stack.  As all the addition and deletion in a stack is done from the top of the stack, the last added element will be first removed from the stack. That is why the stack is also called Last-in-First-out (LIFO).  Note that the most frequently accessible element in the stack is the top most elements, whereas the least accessible element is the bottom of the stack. Definition 2
  • 3.
    Stack Operations 3 Top Stack isempty. Top Add(20) Top Add(33) Top Add(47) Top Delete(47) Top Add(77) Top Delete(77) Top Delete(33) Figure 3.1 Stack operations.
  • 4.
     The insertion(or addition) operation is referred to as push, and the deletion (or remove) operation as pop.  A stack is said to be empty or underflow, if the stack contains no elements. At this point the top of the stack is present at the bottom of the stack.  And it is overflow when the stack becomes full, i.e., no other elements can be pushed onto the stack. At this point the top pointer is at the highest location of the stack. Stack Operations 4
  • 5.
     The primitiveoperations performed on the stack are as follows:  PUSH: The process of adding (or inserting) a new element to the top of the stack is called PUSH operation. Pushing an element to a stack will add the new element at the top. After every push operation the top is incremented by one. If the array is full and no new element can be accommodated, then the stack overflow condition occurs.  POP: The process of deleting (or removing) an element from the top of stack is called POP operation. After every pop operation the stack is decremented by one. If there is no element in the stack and the pop operation is performed then the stack underflow condition occurs. 2.1 Operations Performed on Stack 5
  • 6.
     Stack canbe implemented in two ways: 1. Static implementation (using arrays) — sequential stack 2. Dynamic implementation (using pointers) — linked stack  Static implementation uses arrays to create stack.  a very simple technique but is not a flexible way, the size cannot be varied  static implementation is not an efficient method when resource optimization is concerned (i.e., memory utilization). 2.2 Stack Implementation 6
  • 7.
     For examplea stack is implemented with array size 50. That is before the stack operation begins, memory is allocated for the array of size 50. Now if there are only few elements (say 30) to be stored in the stack, then rest of the statically allocated memory (in this case 20) will be wasted, on the other hand if there are more number of elements to be stored in the stack (say 60) then we cannot change the size array to increase its capacity.  The above said limitations can be overcome by dynamically implementing (is also called linked list representation) the stack using pointers. Example 7
  • 8.
     Suppose STACK[SIZE]is a one dimensional array for implementing the stack, which will hold the data items. TOP is the pointer that points to the top most element of the stack.  Let DATA is the data item to be pushed.  Algorithm for push 1. If TOP = SIZE – 1, then: (a) Display “The stack is in overflow condition” (b) Exit 2. TOP = TOP + 1 3. STACK [TOP] = ITEM 4. Exit 2.3 Stack Using Arrays-Algorithm for push 8
  • 9.
     DATA isthe popped (or deleted) data item from the top of the stack.  Algorithm for pop 1. If TOP < 0, then (a) Display “The Stack is empty” (b) Exit 2. Else remove the Top most element 3. DATA = STACK[TOP] 4. TOP = TOP – 1 5. Exit Stack Using Arrays-Algorithm for pop 9
  • 10.
    insert(int item) { if (top>=n-1){ printf(“Stack Full”); return; }; top=top+1; s[top]=item; return; } Push and Pop - Insert and Delete 10 dele( ) { if (top<0) { printf(“Stack Empty”); return; } item=s[top]; printf(“Deleted item is %d”, item); top=top-1; return; }
  • 11.
    //This program isto demonstrate the operations performed //on the stack and it is implementation using arrays #include<stdio.h> #include<stdlib.h> #include<conio.h> //Defining the maximum size of the stack #define MAXSIZE 100 //Declaring the stack array and top variables in a structure struct stack { int stack[MAXSIZE]; int Top; }; typedef struct stack NODE; Stack Operations-C Program(1) 11
  • 12.
    //This function willadd/insert an element to Top of the stack void push(NODE *pu) { int item; if (pu->Top == MAXSIZE-1) { printf("nThe Stack Is Full."); } else { printf("nEnter The Element To Be Inserted = "); scanf("%d", &item); pu->stack[++pu->Top]=item; } } Stack Operations-C Program(2) 12
  • 13.
    //This function willdelete an element from the Top of the stack void pop(NODE *po) { int item; if (po->Top == -1) printf("nThe Stack Is Empty."); else { item=po->stack[po->Top--]; printf("nThe Deleted Element Is = %d", item); } } Stack Operations-C Program(3) 13
  • 14.
    //This function toprint all the existing elements in the stack void traverse(NODE *pt) { int i; if (pt->Top == -1) printf("nThe Stack is Empty"); else { printf("nnThe Element(s) In The Stack(s) is/are..."); for(i=pt->Top; i>=0; i--) printf ("n %d", pt->stack[i]); } } Stack Operations-C Program(4) 14
  • 15.
    int main( ) { intchoice; char ch; NODE ps; ps.Top=-1; do { system("cls"); printf("n1. PUSH"); //A menu for the stack operations printf("n2. POP"); printf("n3. TRAVERSE"); printf("nEnter Your Choice = "); scanf ("%d", &choice); Stack Operations-C Program(5) 15
  • 16.
    switch(choice) { case 1://Calling push() function by passing the structure pointer to the function push(&ps); break; case 2: //calling pop() function pop(&ps); break; case 3: //calling traverse() function traverse(&ps); break; default: printf("nYou Entered Wrong Choice"); } Stack Operations-C Program(6) 16
  • 17.
    printf("nnPress (Y/y) ToContinue = "); //Removing all characters in the input buffer //for fresh input(s), especially <<Enter>> key fflush(stdin); scanf("%c", &ch); } while(ch == 'Y' || ch == 'y'); } Stack Operations-C Program(7) 17
  • 18.
     Applications ofstacks  Stack is internally used by compiler when any recursive function is executed  If we want to implement a recursive function non- recursively, stack is programmed explicitly.  Stack is also used to evaluate a mathematical expression and to check the parentheses in an expression. 2.4 Applications of Stacks 18
  • 19.
     Recursion occurswhen a function is called by itself repeatedly, the function is called recursive function. The general algorithm model for any recursive function contains the following steps: 1. Prologue: Save the parameters, local variables, and return address. 2. Body: If the base criterion has been reached, then perform the final computation and go to step 3; otherwise, perform the partial computation and go to step 1 (initiate a recursive call). 3. Epilogue: Restore the most recently saved parameters, local variables, and return address. Applications of Stacks- Recursion 19
  • 20.
    Figure 3.2 Flowchartmodel for a recursive algorithm Flowchart model for a recursive algorithm 20
  • 21.
     The Last-in-First-Outcharacteristics of a recursive function points that the stack is the most obvious data structure to implement the recursive function.  As a function calls a (may be or may not be another) function, its arguments, return address and local variables are pushed onto the stack. Since each function runs in its own environment or context, it becomes possible for a function to call itself — a technique known as recursion. This capability is extremely useful and extensively used — because many problems are elegantly specified or solved in a recursive way. Stack and Recursion 21
  • 22.
    // Program tofind factorial of a number, recursively #include<conio.h> #include<iostream> using namespace std; void fact(int no, int facto) { if (no <= 1) { // Final computation cout<<"nThe Factorial is = "<<facto; return; } else { // Partial computation of the program facto=facto*no; fact(--no, facto); // Function call to itself, that is recursion } } Calculating Factorial of n Recursively 22
  • 23.
    int main() { system("cls"); int number,factorial; // Initialization of formal parameters, local variables and etc. factorial=1; cout<<"nEnter the No = "; cin>>number; fact(number, factorial); //Starting point of the function, which calls itself getch(); } Calculating Factorial of n Recursively 23
  • 24.
     Recursion ofcourse is an elegant programming technique, but not the best way to solve a problem, even if it is recursive in nature. This is due to the following reasons: 1. It requires stack implementation. 2. It makes inefficient utilization of memory, as every time a new recursive call is made a new set of local variables is allocated to function. 3. Moreover it also slows down execution speed, as function calls require jumps, and saving the current state of program onto stack before jump. Recursion vs Iteration 24
  • 25.
    Recursion vs Iteration(Cont.) 25 No. Iteration Recursion 1 It is a process of executing a statement or a set of statements repeatedly, until some specified condition is specified. Recursion is the technique of defining anything in terms of itself. 2 Iteration involves four clear-cut steps like initialization, condition, execution, and updating. There must be an exclusive if statement inside the recursive function, specifying stopping condition. 3 Any recursive problem can be solved iteratively. Not all problems have recursive solution. 4 Iterative counterpart of a problem is more efficient in terms of memory utilization and execution speed. Recursion is generally a worse option to go for simple problems, or problems not recursive in nature.
  • 26.
    1. It consumesmore storage space because the recursive calls along with automatic variables are stored on the stack. 2. The computer may run out of memory if the recursive calls are not checked. 3. It is not more efficient in terms of speed and execution time. 4. According to some computer professionals, recursion does not offer any concrete advantage over non-recursive procedures/functions. 5. If proper precautions are not taken, recursion may result in non-terminating iterations. 6. Recursion is not advocated when the problem can be through iteration. Recursion may be treated as a software tool to be applied carefully and selectively. Disadvantages of Recursion 26
  • 27.
     So farwe have discussed the comparative definition and disadvantages of recursion with examples. Now let us look at the Tower of Hanoi problem and see how we can use recursive technique to produce a logical and elegant solution. Tower of Hanoi Problem 27
  • 28.
     three pegs(or towers) X, Y and Z (or A, B and C) exist. There will be n different sized disks. Each disk has a hole in the center so that it can be stacked on any of the pegs. At the beginning, the disks are stacked on the X peg, that is the largest sized disk on the bottom and the smallest sized disk on top.  the rules to be followed during transfer: 1. Transferring the disks from the source peg to the destination peg such that at any point of transformation no large size disk is placed on the smaller one. 2. Only one disk may be moved at a time. 3. Each disk must be stacked on any one of the pegs. Tower of Hanoi Problem 28
  • 29.
     Origins The puzzlewas invented by the French mathematician Édouard Lucas in 1883. There is a story about an Indian temple in Kashi Vishwanath which contains a large room with three time-worn posts in it surrounded by 64 golden disks. Brahmin priests, acting out the command of an ancient prophecy, have been moving these disks, in accordance with the immutable rules of the Brahma, since that time. The puzzle is therefore also known as the Tower of Brahma puzzle. According to the legend, when the last move of the puzzle will be completed, the world will end. It is not clear whether Lucas invented this legend or was inspired by it. From http://en.wikipedia.org/wiki/Tower_of_Hanoi Tower of Hanoi Problem 29
  • 30.
    Tower of HanoiProblem 30
  • 31.
    The Towers ofHanoi: Solution for Two Disks 31
  • 32.
    The Towers ofHanoi: Solution for Three Disks 32
  • 33.
    The Towers ofHanoi: Solution for Five Disks
  • 34.
    #include<stdio.h> int hanoi(int n,char one, char two, char three) { if(n==1) printf("%c --> %cn", one, three); else { hanoi(n-1, one, three, two); printf("%c --> %cn", one, three); hanoi(n-1, two, one, three); } } The Towers of Hanoi-C Program 34 int main() { int n; while(scanf("%d", &n)!=EOF) hanoi(n, 'a', 'b', 'c'); }
  • 35.
     Another applicationof stack is calculation of postfix expression. There are basically three types of notation for an expression (mathematical expression, An expression is defined as the number of operands or data items combined with several operators.) 1. Infix notation 2. Prefix notation 3. Postfix notation  The infix notation is what we come across in our general mathematics, where the operator is written in- between the operands. For example : The expression to add two numbers A and B is written in infix notation as: A + B Expression 35
  • 36.
     The prefixnotation is a notation in which the operator(s) is written before the operands, it is also called polish notation in the honor of the polish mathematician Jan Lukasiewicz who developed this notation. The same expression when written in prefix notation looks like: + A B  In the postfix notation the operator(s) are written after the operands, so it is called the postfix notation (post means after), it is also known as suffix notation or reverse polish notation. The above expression if written in postfix expression looks like: A B + Expression 36
  • 37.
     The prefixand postfix notations are not really as awkward to use as they might look. For example, a C function to return the sum of two variables A and B (passed as argument) is called or invoked by the instruction: add(A, B)  Note that the operator add (name of the function) precedes the operands A and B.  Because the postfix notation is most suitable for a computer to calculate any expression (due to its reverse characteristic), and is the universally accepted notation for designing Arithmetic and Logical Unit (ALU) of the CPU (processor). Expression 37
  • 38.
     Human beingsare quite used to work with mathematical expressions in infix notation, which is rather complex. One has to remember a set of rules while using this notation and it must be applied to expressions in order to determine the final value. These rules include precedence, BODMAS, and associativity.  In a postfix expression operands appear before the operator, so there is no need for operator precedence and other rules.  BODMAS: short for “Brackets ,Division,Multiplication, Addition,Subtraction” Advantages of using postfix notation 38
  • 39.
     The methodof converting infix expression A + B * C to postfix form is: A + B * C Infix Form A + (B * C) Parenthesized expression A + (B C *) Convert the multiplication A (B C *) + Convert the addition A B C * + Postfix form 2.5 Converting Infix To Postfix Expression 39
  • 40.
     The rulesto be remembered during infix to postfix conversion are: 1. Parenthesize the expression starting from left to right. 2. During parenthesizing the expression, the operands associated with operator having higher precedence are first parenthesized. For example in the above expression B*C is parenthesized first before A+B. 3. The sub-expression (part of expression), which has been converted into postfix, is to be treated as single operand. 4. Once the expression is converted to postfix form, remove the parenthesis. The Rule of Converting Infix to Postfix Expression 40
  • 41.
     Example 1: Givepostfix form for A + [ (B + C) + (D + E) * F ] / G  Solution: Evaluation order is A + { [ (BC +) + (DE +) * F ] / G } A + { [ (BC +) + (DE + F *) ] / G } A + [ (BC + DE + F * +) / G ] A + ( BC + DE + F *+ G / ) Postfix Form: ABC + DE + F * + G / + Example 1 41
  • 42.
     Example 2: Givepostfix form for (A + B) * C / D + E ^ A / B  Solution: Evaluation order is [(AB +) * C / D ] + [ (EA ^) / B ] [(AB +) C * / D ] + [ (EA ^) B / ] [(AB +) C * D / ] + [ (EA ^) B / ] (AB +) C * D / (EA ^) B / + Postfix Form: AB + C * D / EA ^ B / + Example 2 42
  • 43.
     Algorithm  SupposeP is an arithmetic expression written in infix notation. This algorithm finds the equivalent postfix expression Q.  Besides operands and operators, P (infix notation) may also contain left and right parentheses.  Assume that the operators in P consists of only exponential ( ^ ), multiplication ( * ), division ( / ), addition ( + ) and subtraction ( - ).  Use a stack to temporarily hold the operators and left parentheses.  The postfix expression Q will be constructed from left to right using the operands from P and operators, which are removed from stack.  Begin by pushing a left parenthesis onto stack and adding a right parenthesis at the end of P. the algorithm is completed when the stack is empty. Algorithm 43
  • 44.
    1. Push “(”onto stack, and add“)” to the end of P. 2. Scan P from left to right and repeat steps 3 to 6 for each element of P until the stack is empty. 3. If an operand is encountered, add it to Q. 4. If a left parenthesis is encountered, push it onto stack. 5. If an operator is encountered, then: ⊗ (a) Repeatedly pop from stack and add Q each operator (on the top of stack), which has the same precedence as, or higher precedence than . ⊗ (b) Add to stack. ⊗ 6. If a right parenthesis is encountered, then: (a) Repeatedly pop from stack and add to Q (on the top of stack until a left parenthesis is encountered. (b) Remove the left parenthesis. [Do not add the left parenthesis to P.] 7. Exit. Note. is used to symbolize any operator in P. ⊗ Algorithm 44
  • 45.
     infix expression:P = A + ( B / C - ( D * E ^ F ) + G ) * H Algorithm 45 Character scanned Stack Postfix Expression Q A + ( B / C – ( D * E ^ F ) + G ) * H ) ( ( + ( + ( ( + ( ( + ( / ( + ( / ( + ( - ( + ( - ( ( + ( - ( ( + ( - ( * ( + ( - ( * ( + ( - ( * ^ ( + ( - ( * ^ ( + ( - ( + ( + ( + ( + ( + ( + * ( + * A A A A B A B A B C A B C / A B C / A B C / D A B C / D A B C / D E A B C / D E A B C / D E F A B C / D E F ^ * A B C / D E F ^ * - A B C / D E F ^ * - G A B C / D E F ^ * - G + A B C / D E F ^ * - G + A B C / D E F ^ * - G + H A B C / D E F ^ * - G + H * +
  • 46.
    // This programis to convert the infix to postfix expression #include<stdio.h> #include<stdlib.h> #include<conio.h> #include<string.h> // Defining the maximum size of the stack #define MAXSIZE 100 // Declaring the stack array and top variables in a structure struct stack { char stack[MAXSIZE]; int Top; }; // type definition allows the user to define an identifier that would // represent an existing data type. The user-defined data type identifier // can later be used to declare variables. typedef struct stack NODE; Infix to Postfix Expression-C Program(1) 46
  • 47.
    // This functionwill add/insert an element to Top of the stack void push(NODE *pu, char item) { if (pu->Top == MAXSIZE-1) { printf("nThe stack is full"); getch(); } else pu->stack[++pu->Top]=item; } // This function will delete an element from the Top of the stack char pop(NODE *po) { char item; if(po->Top == -1) { printf("nThe stack is empty. Invalid infix expression"); exit(0); } else { item=po->stack[po->Top--]; return(item); } } Infix to Postfix Expression-C Program(2) 47
  • 48.
    // This functionreturns the precedence of the operator int prec(char symbol) { switch(symbol) { case '(': return(1); case ')': return(2); case '+': case '-': return(3); case '*': case '/': case '%': return(4); case '^': return(5); default: return(0); } } Infix to Postfix Expression-C Program(3) 48
  • 49.
    // This functionwill return the postfix expression of an infix void Infix_Postfix(char infix[], char postfix[]) { int i,j,len; char ch; NODE ps; ps.Top=-1; len=strlen(infix); infix[len++]=')'; // At the end of the string inputting a parenthesis ')' push(&ps,'('); // Parenthesis is pushed to the stack for(int i=0,j=0;i<len;i++) { switch(prec(infix[i])) { case 1: // Scanned char is '(' push to the stack push(&ps,infix[i]); break; Infix to Postfix Expression-C Program(4) 49
  • 50.
    case 2: //Scanned char is ')' pop the operator(s) and add to the postfix expression ch=pop(&ps); while(ch != '(') { postfix[j++]=ch; ch=pop(&ps); } break; // Scanned operator is +,– then pop the higher or same // precedence operator to add postfix before pushing // the scanned operator to the stack case 3: ch=pop(&ps); while(prec(ch) >= 3) { postfix[j++]=ch; ch=pop(&ps); } push(&ps,ch); push(&ps,infix[i]); break; Infix to Postfix Expression-C Program(5) 50
  • 51.
    // Scanned operatoris *,/,% then pop the higher or // same precedence operator to add postfix before // pushing the scanned operator to the stack case 4: ch=pop(&ps); while(prec(ch) >= 4) { postfix[j++]=ch; ch=pop(&ps); } push(&ps,ch); push(&ps,infix[i]); break; Infix to Postfix Expression-C Program(6) 51
  • 52.
    // Scanned operatoris ^ then pop the same // precedence operator to add to postfix before pushing // the scanned operator to the stack case 5: ch=pop(&ps); while(prec(ch) == 5) { postfix[j++]=ch; ch=pop(&ps); } push(&ps,ch); push(&ps,infix[i]); break; Infix to Postfix Expression-C Program(7) 52
  • 53.
    //Scanned char isa operand simply add to the postfix expression default: postfix[j++]=infix[i]; } } printf("nThe postfix expression is = "); puts(postfix); // Printing the postfix notation to the screen } Infix to Postfix Expression-C Program(8) 53
  • 54.
    int main() { char choice,infix[MAXSIZE],postfix[MAXSIZE]; do { system("cls"); printf("nEnter the infix expression = "); fflush(stdin); gets(infix); // Inputting the infix notation Infix_Postfix(infix, postfix); // Calling the infix to postfix function printf("nDo you want to continue (Y/y) = "); fflush(stdin); scanf("%c", &choice); } while(choice == 'Y' || choice == 'y'); } Infix to Postfix Expression-C Program(9) 54
  • 55.
     Following algorithmfinds the RESULT of an arithmetic expression P written in postfix notation. The algorithm evaluates P by using a STACK to hold operands.  Algorithm: 1. Add a right parenthesis “)” at the end of P. [sentinel.] 2. Scan P from left to right and repeat Steps 3 and 4 for each element of P until the sentinel “)” is encountered. 3. If an operand is encountered, put it on STACK. 4. If an operator is encountered, then: ⊗ (a) Remove the two top elements of STACK, where A is the top element and B is the next-to-top element. (b) Evaluate B A. ⊗ (c) Place the result on to the STACK. 5. Result equal to the top element on STACK. 6. Exit. 2.6 Evaluating Postfix Expression 55
  • 56.
     P= 23 4 * + 9 3 / - example
  • 57.
    // This programis to evaluate postfix expression. // The stack is used and it is implemented using arrays. #include<stdio.h> #include<stdlib.h> #include<math.h> #include<conio.h> #include<string.h> // Defining the maximum size of the stack #define MAXSIZE 100 // Declaring the stack array and top variables in a structure struct stack { int stack[MAXSIZE]; int Top; }; Evaluating Postfix Expression -C Program(1) 57
  • 58.
    // type definitionallows the user to define an identifier that would // represent an existing data type. The user-defined data type identifier // can later be used to declare variables. typedef struct stack NODE; // This function will add/insert an element to Top of the stack void push(NODE *pu,int item) { if (pu->Top == MAXSIZE-1) { printf("nThe stack is full"); getch(); } else pu->stack[++pu->Top]=item; } Evaluating Postfix Expression -C Program(2) 58
  • 59.
    // This functionwill delete an element from the Top of the stack int pop(NODE *po) { int item; if (po->Top==-1) printf("nThe Stack Is Empty. Invalid Infix expression"); else item=po->stack[po->Top--]; return(item); } Evaluating Postfix Expression -C Program(3) 59
  • 60.
    // This functionwill return the postfix expression of an infix int Postfix_Eval(char postfix[]) { int a,b,temp,len; NODE ps; // Declaring an pointer variable to the structure ps.Top=-1; // Initializing the Top pointer to NULL len=strlen(postfix); // Finding length of the string for(int i=0;i<len;i++) { if(postfix[i]<='9' && postfix[i]>='0') push(&ps,(postfix[i]-48)); // Operand is pushed on the stack else { a=pop(&ps); b=pop(&ps);// Pop the top most two operand for operation Evaluating Postfix Expression -C Program(4) 60
  • 61.
    switch(postfix[i]) { case '+':temp=b+a; break; case '-': temp=b-a;break; case '*': temp=b*a;break; case '/': temp=b/a;break; case '%': temp=b%a;break; case '^': temp=pow(b,a); }/*End of switch */ push(&ps,temp); } } return(pop(&ps)); } Evaluating Postfix Expression -C Program(5) 61
  • 62.
    int main() { char choice,postfix[MAXSIZE]; do { system("cls"); printf("nnEnter the Postfix expression="); fflush(stdin); gets(postfix); // Inputting the postfix notation printf("nnThe postfix evaluation is = %d", Postfix_Eval(postfix)); printf("nnDo you want to continue (Y/y) ="); fflush(stdin); scanf("%c", &choice); } while(choice=='Y'||choice=='y'); } Evaluating Postfix Expression -C Program(6) 62