Presentation is loading. Please wait.

Presentation is loading. Please wait.

CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM.

Similar presentations


Presentation on theme: "CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM."— Presentation transcript:

1 CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM

2 What is a stack? A stack is a list of homogeneous elements, wherein the addition and deletion of elements occur only at one end, called top of the stack. Last item placed on the stack will be the first item removed - last in, first out, or simply LIFO. Used to : implement function calls convert recursive algorithms to nonrecursive algorithms, especially recursive algorithms that are not tail recursive. 2

3 example of stacks : a) second tray in a stack of trays can be removed only if the first tray has been removed. b) get to your favorite computer science book, which is underneath your math and history books, you must first remove the math and history books. c) after removing these two books, the computer science book becomes the top book – that is, the top element of the stack. 3

4 Initially, all of the boxes are on the floor and the stack is empty. 4

5 (a) First, we push box A onto the stack. (b) We then push box B onto the stack. (c) Next, we push box C onto the stack. (d) Next, we retrieve the top element of the stack. (e) We then push box D onto the stack. (f) Next, we pop the stack. 5

6 Stack Operation 6 There are several operations on a stack:- Create a stack Check for an empty stack Check for a full stack Pushing process Popping process

7 Implementation of a Stack The implementation of ADT :  must consist of the data structure definition and establishing the basic operations of a Stack.  either using array or linked list. 7

8 Data Structure of a Stack -Array Concept- 8 PART 1

9 Sample Program 1 #define MAXSTACK 10 typedef enum bool{ FALSE, TRUE } Boolean; typedef int StackEntry; typedef int StackIndex; typedef struct stack{ StackIndex top; StackEntry entry[MAXSTACK]; } Stack; Stack mystack; 9 determine the maximum item in the stack to avoid program crash Return True or False Determine top (index) of the stack Size of array “entry”

10 Continue… Several operations that can be performed to a Stack : 1. Create a stack 2. Test for an empty stack 3. Test for a full stack 4. Popping out (delete) an item from the top of a stack 5. Pushing (add) an item onto the top of a stack 6. Clear stack 10 void CreateStack ( Stack *S) { S->top = 0; } void CreateStack ( Stack *S) { S->top = 0; } Boolean EmptyStack ( Stack *S) { return (S->top == 0); } Boolean EmptyStack ( Stack *S) { return (S->top == 0); } Boolean FullStack ( Stack *S) { return (S->top == MAXSTACK); return (S->top == MAXSTACK);} Boolean FullStack ( Stack *S) { return (S->top == MAXSTACK); return (S->top == MAXSTACK);} void pop ( Stack *S, StackEntry *X ) { if (S->top == 0) if (S->top == 0) printf (“Attempt to pop from empty Stack”); else { --(S->top); *X = S->entry[S->top]; }} void pop ( Stack *S, StackEntry *X ) { if (S->top == 0) if (S->top == 0) printf (“Attempt to pop from empty Stack”); else { --(S->top); *X = S->entry[S->top]; }} void push (Stack *S, StackEntry X ) { if (S->top == MAXSTACK) if (S->top == MAXSTACK) printf (“Attempt to push new item onto a full Stack”); else { S->entry[S->top] = X ; ++(S->top);}} void push (Stack *S, StackEntry X ) { if (S->top == MAXSTACK) if (S->top == MAXSTACK) printf (“Attempt to push new item onto a full Stack”); else { S->entry[S->top] = X ; ++(S->top);}} void Clear_Stack(Stack *S) { StackEntry p; while( ! EmptyStack(S)) { Pop(&S, &p); printf(“%d”, p); }} void Clear_Stack(Stack *S) { StackEntry p; while( ! EmptyStack(S)) { Pop(&S, &p); printf(“%d”, p); }}

11 Sample program 2 #define MAX 5 //size of array = 5 typedef enum bool { FALSE, TRUE } Boolean; typedef struct stack { int index; int item[MAX]; } Stack; Stack mystack; 11

12 Continue.. void CreateStack ( Stack *S) { S->index = 0; } Boolean EmptyStack ( Stack *S) { return (S->index == 0); } Boolean FullStack ( Stack *S) { return (S->index == MAX); } void pop ( Stack *S, int *X ){ if (!EmptyStack (S)) { --(S->index); *X = S->item[S->index]; } else printf("Stack is Empty!\n"); } 12 void push (Stack *S, int X ){ if (!FullStack (S)) { S->item[S->index] = X ; ++(S->index); } else printf("Stack is full!\n"); } void Clear_Stack(Stack *S){ int p; while( ! EmptyStack(S)) { pop(&S, &p); printf("%d", p); } void main() { int i = 0,a=3, b=5, c=6; CreateStack(&mystack); push(&mystack,a); push(&mystack,b+c); pop(&mystack,&a); }

13 EXERCISE!! 13 PART 1

14 Question 1 14 Draw a sequence of stack frame to show the progress of each of following code segments. CreateStack (&my); push (&my, ‘z’); push (&my, ‘r’); push (&my, ‘t’); pop (&my, &a); push (&my, a); pop (&my, &c);

15 Question 2 15 What is the final value of a, b and c? int a=16, b=5, c=8; CreateStack(&mystack); push(&mystack,9); push(&mystack,c); push(&mystack,b+c); pop(&mystack,&c); push(&mystack,11); pop(&mystack,&b); pop(&mystack,&a); push(&mystack,a); push(&mystack,pow(b-5,2)); pop(&mystack,&a); printf("\n%d %d %d\n", a, b, c);

16 Stack Application 16 PART 2

17 Checking for a balance parenthesis in mathematics expression Algorithm: Begin If the token is “(“ or “{“ or “[“ then push onto the stack If the token is “)”or “}”or”]” then Pop the token from the stack Compare the pop item with the current token, If do not match print error message Else continue with next token If the stack is empty by the time we get to the end of the expression, and all pairs were of the same type, the expression is properly balanced. Otherwise, the expression is not a valid expression. End 17

18 Checking for a balance parenthesis in mathematics expression Example: 1. (A + B) – C ) 2. A * (C – D) 18

19 Example of infix expression: A + B * C Step 1 results in ( A + ( B * C ) ) Step 2 moves the multiply operator after C ( A + ( B C * ) ) And then moves the addition operator to between the last two closing parenthesis. This change is made because the closing parenthesis for the plus is the last parenthesis. We now have ( A ( B C * ) +) Finally, Step 3, removes the parentheses A B C * + 19

20 Conversion of infix Notations 20 Postfixsinfixs A B + A B * C + A B C * + A B + C * A + B A * B + C A + B * C ( A + B ) * C

21 Infix to postfix Transformation (Algorithmic Transformation) The rules: ◦ Fully parenthesize the expression using any explicit parentheses and the arithmetic precedence – (),*,/,+,- ◦ Change all infix notation in each parenthesis to postfix notation, starting from the innermost expressions. Conversion to postfix notation is done by moving the operator to the location of the expression’s closing parenthesis. ◦ Remove all parentheses 21

22 Converting infix to postfix expression Algorithm: Begin Create a new Stack( empty stack) While not error and not end of expression, do Retrieve the following token if token is equal to ‘(‘ : Push onto Stack ‘)’ : Pop out and display items from the Stack until “(” is encounter in the Stack, but do not display “(“, display error if “(“ is not found Operator *,/,+,- : If emptyStack or current token is in higher priority compare to the top of the stack, Push token to the Stack else pop top item from stack and display, Repeat this comparison with the remaining item. Operand : Display the Operand Pop the remaining items from the stack. End 22

23 Infix to postfix Transformation (Algorithmic Transformation) 23 ConditionAction Precedence of operator or “(“ > top element in the stack Push onto the stack “)” the top element of the stack is popped and inserted to postfix string; is continued until left parenthesis is encountered at the top of the stock when it is popped and discarded Precedence of operator = or < top element in the stack The top stack element is popped and inserted to postfix string. Compare scanned character with new top element, if top >scanned character, it is popped and add to postfix string. (repeated until the top element of the stack has lower precedence than the scanned character when it is pushed on to the stack ) When the end of the string is reached all the elements of the stack are popped and inserted into the postfix string in order.

24 Evaluating Postfix Notation (manually) ex1: 24 Postfix 1 3 * 4 - 1 3 * 34 - Prove using infix 1 * 3 - 4 3 - 4

25 ex2: 25 9 3 5 + / 2 * Postfix Prove using infix 3 5 + 8 9 / ( 3 + 5 ) * 2 9 / 8 9/ 1 2 * 2 1 * 2 2

26 EXERCISE TIME!!! If the values of A, B, C and D are 2,3,4,5, respectively, manually calculate the value of the following postfix expressions: A B * C – D + A B C + * D - 26

27 Converting infix to postfix expression set of rules: If token is an operand Push token If data is an operator Pop the first top two elements Do Computation Push result And the final result should be the only data in the stack where the value of top is 0 27

28 A + B * C => A B C * + Copy operand A to output expression Push operator + into stack Copy operand B to output expression Push operator * into stack (priority of * is higher than +) Copy operand C to output expression Pop operator * and copy to output expression Pop operator + and copy to output expression 28

29 We have a an array to represent stack 29 A variable to keep track the index of the top element Rules: If data scanned is an operand display on screen If data scanned is an operator Check w/ the top element If same level or lowest priority? Pop top element Else Push data At the end, the stack MUST be emptied top

30 ex1: Assume an infix notation A+B 30 A+B TOP 0 STACK 0 1 2 3 Output A + B+

31 ex2: A + B * C 31 data A + B * C TOP 0 1 0 Output STACK 0 1 2 3 A + B*C*+

32 Evaluation of postfix expression Algorithm Begin Create an empty stack Do while not end of expression encounter Gets the next token in the expression If token is a operand Push onto stack If token is an operator do: pop the top two items from stack execute the expression push the result onto stack if the end of the expression is encountered, the final value for the expression is equal to the top value of the stack End 32

33 Example Evaluate the result of the following postfix notation.  3 2 + 5 – 7 +  5 7 9 + 8 - * 33

34 EXERCISE!! 34 PART 2

35 EXERCISE 1 Using manual transformation, write the following infix expression in their postfix and prefix forms: D – B + C A * B + C * D (A + B) * C – D * F + C (A – 2 * (B + C) – D * E) * F 35

36 EXERCISE 2 Convert the following infix expression to postfix expression. (A * (B + (C / D) ) ) (2 * a) / ((a + b) * (a - c)) 36

37 EXERCISE 3 Evaluate the result of the following postfix notation. 3 2 + 5 – 7 + 5 7 9 + 8 - * 37

38 Data Structure of a Stack -Linked List Concept- 38 PART 3

39 Sample Program 1 typedef enum bool{ FALSE, TRUE } Boolean; typedef int StackEntry; typedef struct node { StackEntry data; struct node *next; } typedef struct stack{ Node *top; } Stack; 39 Return True or False node structure

40 Continue… Several operations that can be performed to a Stack : 1. Create a stack 2. Test for an empty stack 3. Test for a full stack 4. Push 5. Pop 6. Clear stack 40 void CreateStack ( Stack *S) { S->top = NULL; } void CreateStack ( Stack *S) { S->top = NULL; } Boolean EmptyStack ( Stack *S) { return (S->top == NULL); return (S->top == NULL);} Boolean EmptyStack ( Stack *S) { return (S->top == NULL); return (S->top == NULL);} Boolean FullStack (void) { Node *np; if ((np = malloc(sizeof(Node))) == NULL) if ((np = malloc(sizeof(Node))) == NULL) return (TRUE); return (TRUE); else { else { free(np); np=NULL; free(np); np=NULL; return (FALSE); return (FALSE); } } Boolean FullStack (void) { Node *np; if ((np = malloc(sizeof(Node))) == NULL) if ((np = malloc(sizeof(Node))) == NULL) return (TRUE); return (TRUE); else { else { free(np); np=NULL; free(np); np=NULL; return (FALSE); return (FALSE); } } void Pop(Stack *s, StackEntry *item) { Node *np; if (s->top == NULL) if (s->top == NULL) Error("Attempt to pop from an empty Stack."); Error("Attempt to pop from an empty Stack."); else { np = s->top; else { np = s->top; s->top = np->next; s->top = np->next; *item = np->entry; *item = np->entry; free(np); free(np); np=NULL; np=NULL; }} void Pop(Stack *s, StackEntry *item) { Node *np; if (s->top == NULL) if (s->top == NULL) Error("Attempt to pop from an empty Stack."); Error("Attempt to pop from an empty Stack."); else { np = s->top; else { np = s->top; s->top = np->next; s->top = np->next; *item = np->entry; *item = np->entry; free(np); free(np); np=NULL; np=NULL; }} void Push(Stack *s, StackEntry item) { Node *np; { Node *np; np = MakeNode(item); np = MakeNode(item); if (np == NULL) if (np == NULL) printf("Attempted to push a non-existing node, printf("Attempted to push a non-existing node, memory is full."); memory is full."); else { np->next = s->top; else { np->next = s->top; s->top = np; s->top = np; }} void Push(Stack *s, StackEntry item) { Node *np; { Node *np; np = MakeNode(item); np = MakeNode(item); if (np == NULL) if (np == NULL) printf("Attempted to push a non-existing node, printf("Attempted to push a non-existing node, memory is full."); memory is full."); else { np->next = s->top; else { np->next = s->top; s->top = np; s->top = np; }} void ClearStack(Stack *s) { Node *np, *fp; { Node *np, *fp; np=s->top; np=s->top; while (np != NULL){ while (np != NULL){ fp = np; fp = np; np = np->next; np = np->next; free(fp); free(fp); fp=NULL; fp=NULL; }} void ClearStack(Stack *s) { Node *np, *fp; { Node *np, *fp; np=s->top; np=s->top; while (np != NULL){ while (np != NULL){ fp = np; fp = np; np = np->next; np = np->next; free(fp); free(fp); fp=NULL; fp=NULL; }}

41 Sample program 2 #include typedef enum bool { FALSE, TRUE }Boolean; typedef struct node { int data; struct node *next; } Node; 41

42 Node *newnode(int value) { …. return temp; } void CreateStack (Node **top) { *top = NULL; } Boolean Empty (Node **top) { return (*top == NULL); } Boolean Full () { Node *temp; if (temp = malloc (sizeof(Node*)) == NULL) return (TRUE); else { free (temp); return FALSE; } 42 void push (Node **top, int value) { Node *temp; temp = newnode(value); temp = newnode(value); if (Full ()) if (Full ()) printf("Memory full"); printf("Memory full"); else { temp->next = *top; else { temp->next = *top; *top = temp; *top = temp;}} void pop (Node **top, int *var) { Node *temp; Node *temp; if (Empty (&top)) if (Empty (&top)) printf("No data..empty!"); else { temp = *top; else { temp = *top; *top = temp->next; *top = temp->next; *var = temp->data; *var = temp->data; free(temp); free(temp);}} void main() { Node *top; int i = 0,a=3, b=5, c=6; CreateStack(&top); push(&top,a); push(&top,b+c); pop(&top,&a); }

43 That’s all for today TQ.. 43


Download ppt "CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM."

Similar presentations


Ads by Google