Stack.

Slides:



Advertisements
Similar presentations
INFIX, PREFIX, & POSTFIX EXPRESSIONS. Infix Notation We usually write algebraic expressions like this: a + b This is called infix notation, because the.
Advertisements

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.
COMPSCI 105 S Principles of Computer Science 13 Stacks.
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.
Topic 15 Implementing and Using Stacks
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
The Stack and Queue Types Lecture 10 Hartmut Kaiser
Stack Applications.
1 Stacks – Chapter 3 A stack is a data structure in which all insertions and deletions of entries are made at one end, called the top of the stack. Alternatively,
CSC 205 Programming II Postfix Expressions. Recap: Stack Stack features Orderly linear structure Access from one side only – top item Stack operations.
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 Structures. The Stack: Definition A stack is an ordered collection of items into which new items may be inserted and from which items may be deleted.
DATA STRUCTURE & ALGORITHMS CHAPTER 3: STACKS. 2 Objectives In this chapter, you will: Learn about stacks Examine various stack operations Discover stack.
Stacks  Introduction  Applications  Implementations  Complex Applications.
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.
EENG212 Algorithms and Data Structures
Data Structures Stack Namiq Sultan 1. Data Structure Definition: Data structures is a study of different methods of organizing the data and possible operations.
CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 19: Stacks and Queues (part 2)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 2)
Stacks An Abstract Data Type. Restricted Access Unlike arrays, stacks only allow the top most item to be accessed at any time The interface of a stack.
CE 221 Data Structures and Algorithms Chapter 3: Lists, Stacks, and Queues - II Text: Read Weiss, §3.6 1Izmir University of Economics.
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.
Stacks Objective After this lecture you will be able to: Describe a stack Describe the representation of stack using linear array Describe the representation.
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.
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.
Review Use of Stack Introduction Stack in our life Stack Operations
Stacks Access is allowed only at one point of the structure, normally termed the top of the stack access to the most recently added item only Operations.
Stacks Chapter 5.
Revised based on textbook author’s notes.
Infix to postfix conversion
Data Structures 5th Week
CE 221 Data Structures and Algorithms
CS 201 Data Structures and Algorithms
MEMORY REPRESENTATION OF STACKS
Hassan Khosravi / Geoffrey Tien
Stacks Chapter 7 introduces the stack data type.
Stacks.
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Data Structures – Week #3
Algorithms and Data Structures
PART II STACK APPLICATIONS
Stack.
COMPUTER 2430 Object Oriented Programming and Data Structures I
Stacks Chapter 5 Adapted from Pearson Education, Inc.
Stack A data structure in which elements are inserted and removed only at one end (called the top). Enforces Last-In-First-Out (LIFO) Uses of Stacks Evaluating.
COMPUTER 2430 Object Oriented Programming and Data Structures I
Stacks and Queues 1.
Queue Applications Lecture 31 Mon, Apr 9, 2007.
Stacks.
Topic 15 Implementing and Using Stacks
CE 221 Data Structures and Algorithms
Jordi Cortadella and Jordi Petit Department of Computer Science
Queue Applications Lecture 31 Tue, Apr 11, 2006.
Infix to postfix conversion
Binary Tree Traversal.
Data Structures and Algorithms 2/2561
17CS1102 DATA STRUCTURES © 2016 KL University – The contents of this presentation are an intellectual and copyrighted property of KL University. ALL RIGHTS.
Chapter 7 (continued) © 2011 Pearson Addison-Wesley. All rights reserved.
Stacks A stack is an ordered set of elements, for which only the last element placed into the stack is accessible. The stack data type is also known as.
Presentation transcript:

Stack

What is Stack? Definition A collection of elements that are inserted and removed according to the last- in first-out (LIFO) principle. The last element will be the first element to be removed. Input and output are only possible at the top on the stack. A B C D

What is Stack? Terminology How does the stack work? Top: The top of stack (default = -1) Push: Insert an item on the top. Pop: Remove the item on the top. How does the stack work? 5 5 2 5 2 3 5 2 5 2 7 top top top top A top top Empty Push 5 Push 2 Push 3 Pop Push 7

What is Stack? Operations InitStack: Make stack empty. IsFull: Check whether stack is full. IsEmpty: Check whether stack is empty. Peek: Read the item at the top. Push: Insert an item at the top. Pop: Remove the item at the top. 5 2 7 Q: Can we access items other than at the top? A: By definition, No. top

Array-based Implementation Stack representation 0 1 2 3 4 … MAX_STACK-1 -1 top items[] #define MAX_STACK 100 typedef enum { false, true } bool; typedef int Data; typedef struct { Data items[MAX_STACK]; int top; } Stack;

Array-based Implementation Operations // Make stack empty. void InitStack(Stack *pstack); // Check whether stack is full. bool IsFull(Stack *pstack); // check whether stack is empty. bool IsEmpty(Stack *pstack); // Read the item at the top. Data Peek(Stack *pstack); // Insert an item at the top. void Push(Stack *pstack, Data item); // Remove the item at the top. void Pop(Stack *pstack);

Array-based Implementation Initialize and IsFull operations // Make stack empty. void InitStack(Stack *pstack) { pstack->top = -1; } A top 8 top 5 2 7 // Check whether stack is full. bool IsFull(Stack *pstack) { return pstack->top == MAX_STACK - 1; }

Array-based Implementation IsEmpty and Peek operations // check whether stack is empty bool IsEmpty(Stack *pstack) { return pstack->top == -1; } A top // Read the item at the top. Data Peek(Stack *pstack) { if (IsEmpty(pstack)) exit(1); //error: empty stack return pstack->items[pstack->top]; } top 5 2 7

Array-based Implementation Push operation // Insert an item at the top. void Push(Stack *pstack, Data item) { if (IsFull(pstack)) exit(1); //error: stack full pstack->items[++(pstack->top)] = item; } 5 2 5 2 3 5 2 3 7 top top top Push 3 Push 7

Array-based Implementation Pop operation // Remove the item at the top. void Pop(Stack *pstack) { if (IsEmpty(pstack)) exit(1); //error: empty stack --(pstack->top); } 5 2 3 7 top 5 2 3 5 2 top top Pop Pop

Print a Reverse String Print a string in the reverse order. E.g., abcd  dcba How to do this with a stack? Push all characters into stack. Read the top, print it and pop until stack is empty. a a b a b c a b c d a b c d a b c a b a Push a Push b Push c Push d Peek, Print & Pop Peek, Print & Pop Peek, Print & Pop Peek, Print & Pop Empty

Print a Reverse String Implementation void ReversePrint(char* s, int len) { Stack stack; char ch; InitStack(&stack);// Make a stack empty. for (int i = 0; i < len; i++) // Push characters. Push(&stack, s[i]); while (!IsEmpty(&stack))// Pop characters. ch = Peek(&stack); printf("%c", ch); Pop(&stack); }

Parenthesis Matching Problem Example Check if each opening symbol has a corresponding closing symbol and the pairs of parentheses are nested properly. Example Balanced: (()()()()), (((()))), (()((())())) Unbalanced: ((((((()), ())), (()()(() ( ( ) ( ( ) ) ( ) ) Most recent open matches first close First open waits until last close

Parenthesis Matching How to do this with a stack? Push all open symbols into stack. Whenever finding the close symbol, pop the open symbol. If the stack is empty, it is not balanced. After reading all parentheses, check the status of the stack. If the stack is empty, it is balanced. Otherwise, it is not balanced. Example: ( ( ( ) ( ) ) ) ( ( ( ( ( ( ( Push ( Push ( Push ( Pop Push ( Pop Pop Pop Empty

Parenthesis Matching Implementation bool IsParanBalanced(char* exp, int len) { Stack stack; InitStack(&stack); // Make a stack empty. for (int i = 0; i < len; i++) { if (exp[i] == '(') // Check open symbol Push(&stack, exp[i]); else if (exp[i] == ')') { // Check close symbol if (IsEmpty(&stack)) return false; // Unbalanced case else Pop(&stack); } return true; // Balanced case return false; // Unbalanced case

Maze Solving Problem Representation Find a path from the starting positon to the goal point position. At any moment, you can only move one step in one of four directions (up, down, left, and right). Representation The maze is represented by a 2D binary array. 0: path, 1: block X 1 Starting Goal

Maze Solving How to do this with a stack? Pop (1, 1) Pop (1, 2) 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 (1, 2) (2, 1) (2, 1) (1, 3) Pop (1, 1) Pop (1, 2) Pop (1, 3) (1, 1) Push right direction. Push down and right direction. Push right direction.

Maze Solving How to do this with a stack? Pop (1, 4) Pop (2, 3) 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 (2, 3) (1, 4) (1, 1) (2, 3) (2, 1) (2, 1) (3, 3) Pop (1, 4) Pop (2, 3) Pop (3, 3) Push down and right direction. Push down direction.

Maze Solving How to do this with a stack? Pop (3, 4) Pop (3, 5) 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 (4, 3) (2, 1) (3, 4) (3, 5) (4, 3) (2, 1) (2, 1) Pop (3, 4) Pop (3, 5) (4, 3) Push down and right direction. Push right direction.

Maze Solving Overall process 1. When extending the path, push a new position on the stack. 1.1. At the current position, extend the path one step by trying to go three directions (up, down, or right). 2. Pop a position to move the current position. 3. If none of the neighboring positions is available, pop a position on the stack. 3.1. If the stack is empty, it indicates failure. Repeat steps 1~3 until the goal has been reached.

Evaluation of Expression How to evaluate the expression? Evaluation by human Assign to each operator a priority. Use parenthesis and evaluate inner-most ones. How to evaluate by computer? How to evaluate the operators with parenthesis How to determine the precedence of operators 3 + 4 * ( 5 / 2 ) + ( 7 + 9 * 3 ) ( ( 3 + ( 4 * ( 5 / 2 ) ) ) + ( 7 + ( 9 * 3 ) ) )

Infix, Postfix, and Prefix Infix notation: X + Y Operators are written in-between their operands. Need extra information to make the order of evaluation of the operators clear. Postfix notation: X Y + Operators are written after their operands. The order of evaluation of operators is always left-to-right. Unnecessary to use parenthesis and precedence of operators. Prefix notation: + X Y Operators are written before their operands. As for postfix, operators are evaluated left-to-right.

Infix vs. Postfix Example Why is postfix useful? No parenthesis is needed No precedence of operators is needed Infix Postfix Prefix A * B + C / D A B * C D / + + * A B / C D A * (B + C) / D A B C + * D / / * A + B C D A * (B + C / D) A B C D / + * * A + B / C D A * B / C – D A B * C / D - - / * A B C D

Converting Infix to Postfix Applying the conversion rule in a recursive way Example Operand_1 Operator Operand_2  Operand_1 Operand_2 Operator ( 4 - 3 ) * 5 4 3 - 5 * ( 4 - 3 ) 5 * 4 3 -

How to Evaluate Postfix Notation Overall process 1. Push operands on the stack until finding an operator. 2. If the operator is found, pop two operands and evaluate the operator. Then, push the result on the stack. Repeat steps 1~2 until reading all characters in postfix notation.

How to Evaluate Postfix Notation Example: 2 3 4 * + Push operands on the stack until finding an operator. If the operator is found, pop two operands and evaluate the operator. Then, push the result on the stack. 2 3 4 * + 2 3 4 * + 2 3 4 * + 2 3 4 * + 2 3 4 * + 2 2 3 2 3 4 2 12 14 Push 2 Push 3 Push 4 Pop Pop Pop Pop Eval: 3 * 4 Eval: 2 + 12 Push 12 Push 14

How to Evaluate Postfix Notation Example: 2 3 + 4 * Push operands on the stack until finding an operator. If the operator is found, pop two operands and evaluate the operator. Then, push the result on the stack. 2 3 + 4 * 2 3 + 4 * 2 3 + 4 * 2 3 + 4 * 2 3 + 4 * 2 2 3 5 5 4 20 Push 2 Push 3 Pop Push 4 Pop Pop Pop Eval: 2 + 3 Eval: 4 * 5 Push 5 Push 20

How to Evaluate Postfix Notation int EvalPostfix(char* exp, int len) { Stack stack; int op1, op2; InitStack(&stack); for (int i = 0; i < len; i++) { if (isdigit(exp[i])) // Push an operand. Push(&stack, exp[i] - '0'); else { // Evaluate an operator. op2 = Peek(&stack); Pop(&stack); op1 = Peek(&stack); Pop(&stack); if (exp[i] == '+') Push(&stack, op1 + op2); else if (exp[i] == '-') Push(&stack, op1 - op2); else if (exp[i] == '*') Push(&stack, op1 * op2); else if (exp[i] == '/') Push(&stack, op1 / op2); } return Peek(&stack);

Converting Infix to Postfix Overall process 1. If the operand is found, print it. 2. If the operator is found, push it into stack, but before pushing 2.1. See the operator at the top of the stack. 2.2. If the priority of the incoming operator is lower than or equal to the top, pop and print the top and go to step 2.1. Repeat steps 1~2 until reading all characters in infix notation. 3. At the end of the infix notation, pop all operators.

Converting Infix to Postfix Example: 2 + 3 * 4 While reading a character form infix notation If we find operand, print it. Otherwise, check the priority of operator and determine whether push it into stack. Pop all operators at the end of the infix notation. 2 + 3 * 4 2 + 3 * 4 2 + 3 * 4 2 + 3 * 4 2 + 3 * 4 2 + 3 * 4 + + + * + * + * Print 2 Compare the priority with top. Print 3 Compare the priority with top. Print 4 Pop all, and print them. 2 Push + 2 3 Push * 2 3 4 2 3 4 * +

Converting Infix to Postfix Example: 2 * 3 + 4 While reading a character form infix notation If we find operand, print it. Otherwise, check the priority of operator and determine whether push it into stack. Pop all operators at the end of the infix notation. 2 * 3 + 4 2 * 3 + 4 2 * 3 + 4 2 * 3 + 4 2 * 3 + 4 2 * 3 + 4 * * + + + Print 2 Compare the priority with top. Print 3 Compare the priority with top. Print 4 Pop all, and print them. 2 Push * 2 3 Pop * 2 3 * 4 2 3 * 4 + Push +

Converting Infix to Postfix Implementation void ConvInfixToPostfix(char* exp, char* convExp, int len) { Stack stack; int idx = 0; InitStack(&stack); for (int i = 0; i < len; i++) if (isdigit(exp[i])) convExp[idx++] = exp[i]; // Print an operand. else { while (!IsEmpty(&stack) && ComPriority(Peek(&stack), exp[i])) { convExp[idx++] = Peek(&stack); // Print an operator. Pop(&stack); // Pop an operator. } Push(&stack, exp[i]); // Push an operator. while (!IsEmpty(&stack)) {

Converting Infix to Postfix Implementation int GetPriority(char op) { if (op == '*' || op == '/') return 2; else if (op == '+' || op == '-') return 1; else return 0; } bool ComparePriority(char op1, char op2) int op1_pr = GetPriority(op1); int op2_pr = GetPriority(op2); if (op1_pr >= op2_pr) return true; return false;