CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM.

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

§3 The Stack ADT 1. ADT A stack is a Last-In-First-Out (LIFO) list, that is, an ordered list in which insertions and deletions are.
CSCE 3110 Data Structures & Algorithm Analysis Stacks and Queues Reading: Chap.3 Weiss.
Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
Stacks Chapter 11.
Arithmetic Expressions Infix form –operand operator operand 2+3 or a+b –Need precedence rules –May use parentheses 4*(3+5) or a*(b+c)
COSC 2006 Chapter 7 Stacks III
Stacks Example: Stack of plates in cafeteria.
C o n f i d e n t i a l Developed By Nitendra NextHome Subject Name: Data Structure Using C Title : Overview of Stack.
E.G.M. Petrakislists, stacks, queues1 Stacks Stack: restricted variant of list –Elements may by inserted or deleted from only one end  LIFO lists –Top:
Chapter 6: Stacks STACK APPLICATIONS STACK IMPLEMENTATIONS CS
Topic 15 Implementing and Using Stacks
E.G.M. Petrakisstacks, queues1 Stacks  Stack: restricted variant of list  elements may by inserted or deleted from only one end : LIFO lists  top: the.
Infix, Postfix, Prefix.
Stacks Chapter Chapter Contents Specifications of the ADT Stack Using a Stack to Process Algebraic Expressions Checking for Balanced Parentheses,
Topic 15 Implementing and Using Stacks
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Stacks.
The Stack and Queue Types Lecture 10 Hartmut Kaiser
Objectives of these slides:
Ceng-112 Data Structures ITurgut Kalfaoglu 1 Chapter 3 Stacks.
Comp 245 Data Structures Stacks. What is a Stack? A LIFO (last in, first out) structure Access (storage or retrieval) may only take place at the TOP NO.
Stack Applications.
1 Stacks Chapter 4 2 Introduction Consider a program to model a switching yard –Has main line and siding –Cars may be shunted, removed at any time.
CSC 205 Programming II Postfix Expressions. Recap: Stack Stack features Orderly linear structure Access from one side only – top item Stack operations.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Chapter 4 Stacks Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving. Its called.
Computer Science Department Data Structure & Algorithms Problem Solving with Stack.
DATA STRUCTURE & ALGORITHMS CHAPTER 3: STACKS. 2 Objectives In this chapter, you will: Learn about stacks Examine various stack operations Discover stack.
Stacks 1. Stack  What is a stack? An ordered list where insertions and deletions occur at one end called the top. Also known as last-in-first-out (LIFO)
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
CSC 211 Data Structures Lecture 23
Infix to postfix conversion Scan the Infix expression left to right If the character x is an operand  Output the character into the Postfix Expression.
Data Structures – Week #3 Stacks. 9.Mart.2012Borahan Tümer, Ph.D.2 Outline Stacks Operations on Stacks Array Implementation of Stacks Linked List Implementation.
Stack Any Other Data Structure Array Linked List
1 CS 132 Spring 2008 Chapter 7 Stacks Read p Problems 1-7.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 2)
CE 221 Data Structures and Algorithms Chapter 3: Lists, Stacks, and Queues - II Text: Read Weiss, §3.6 1Izmir University of Economics.
Copyright © Curt Hill Stacks An Useful Abstract Data Type.
CHP-3 STACKS.
Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving data LIFO (Last In First Out) structure.
Data Structures: A Pseudocode Approach with C1 Chapter 3 Objectives Upon completion you will be able to Explain the design, use, and operation of a stack.
Prof. I. J. Chung Data Structure #5 Professor I. J. Chung.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
CC 215 DATA STRUCTURES MORE ABOUT STACK APPLICATIONS Dr. Manal Helal - Fall 2014 Lecture 6 AASTMT Engineering and Technology College 1.
Stacks Chapter 3 Objectives Upon completion you will be able to
Applications of Stack Maitrayee Mukerji. Stacks Last In First Out (LIFO List) ◦ FILO? Insertions and Deletions from the same end called the Top Push(),
CE 221 Data Structures and Algorithms Chapter 3: Lists, Stacks, and Queues - II Text: Read Weiss, §3.6 1Izmir University of Economics.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
COMPSCI 107 Computer Science Fundamentals
Infix to postfix conversion
MEMORY REPRESENTATION OF STACKS
Stacks.
CSC 172 DATA STRUCTURES.
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Stacks Stack: restricted variant of list
Stacks Chapter 4.
Data Structures – Week #3
Stack application: postponing data usage
Algorithms and Data Structures
STACK CHAPTER 03 Developed By :- Misha Ann Alexander Data Structures.
Visit for more Learning Resources
PART II STACK APPLICATIONS
Stacks Chapter 5 Adapted from Pearson Education, Inc.
Stacks and Queues 1.
Stacks.
Topic 15 Implementing and Using Stacks
(Part 2) Infix, Prefix & Postfix
Stack.
Data Structures – Week #3
Chapter 7 (continued) © 2011 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM

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

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

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

(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

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

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

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

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”

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

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

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

EXERCISE!! 13 PART 1

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);

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);

Stack Application 16 PART 2

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

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

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

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

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

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

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.

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

ex2: / 2 * Postfix Prove using infix / ( ) * 2 9 / 8 9/ 1 2 * 2 1 * 2 2

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

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

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

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

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

ex2: A + B * C 31 data A + B * C TOP Output STACK A + B*C*+

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

Example Evaluate the result of the following postfix notation.  – 7 +  * 33

EXERCISE!! 34 PART 2

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

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

EXERCISE 3 Evaluate the result of the following postfix notation – * 37

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

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

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; }}

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

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

That’s all for today TQ.. 43