1 Introduction to Stacks What is a Stack? Stack implementation using array. Stack implementation using linked list. Applications of Stacks.

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

Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
Expression Trees What is an Expression tree? Expression tree implementation Why expression trees? Evaluating an expression tree (pseudo code) Prefix, Infix,
Stacks Chapter 11.
COSC 2006 Chapter 7 Stacks III
Topic 15 Implementing and Using Stacks
Introduction to Stacks What is a Stack Stack implementation using arrays. Application of Stack.
Introduction to Stacks What are Stacks? Stack implementation using arrays. Stack application.
Infix, Postfix, Prefix.
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Introduction to Stacks What is a Stack Stack implementation using array. Stack implementation using linked list. Applications of Stack.
Stacks Chapter Chapter Contents Specifications of the ADT Stack Using a Stack to Process Algebraic Expressions Checking for Balanced Parentheses,
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Queues What is a queue? Queue Implementations: –As Array –As Circular Array –As Linked List Applications of Queues. Priority queues.
1 Stacks Stack Applications Evaluating Postfix Expressions Introduction to Project 2 Reading: L&C Section 3.2,
Main Index Contents 11 Main Index Contents Stacks Further Stack Examples Further Stack Examples Pushing/Popping a Stack Pushing/Popping a Stack Class StackClass.
Queues What is a Queue? Queue Implementations: Queue As Array
The Stack and Queue Types Lecture 10 Hartmut Kaiser
Stack  A stack is a linear data structure or abstract data type for collection of items, with the restriction that items can be added one at a time and.
Data Structures Using C++ 2E Chapter 7 Stacks. Data Structures Using C++ 2E2 Objectives Learn about stacks Examine various stack operations Learn how.
Exam 1 –Monday June 25 th –open Book / Open Notes –No Electronic Devices (calculators, laptops, etc) –Room Number: W –Time: 5:30pm to 8:00pm.
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.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
Stack Applications.
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.
Ics202 Data Structures. U n i v e r s i t y o f H a i l 1. Stacks top push (8)push (2)
Computer Science Department Data Structure & Algorithms Problem Solving with Stack.
SAK 3117 Data Structures Chapter 3: STACKS. Objective To introduce: Stack concepts Stack operations Stack applications CONTENT 3.1 Introduction 3.2 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)
Information and Computer Sciences University of Hawaii, Manoa
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.
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.
Click to edit Master text styles Stacks Data Structure.
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(),
U n i v e r s i t y o f H a i l 1 ICS 202  2011 spring  Data Structures and Algorithms 
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.
Stacks Stack Abstract Data Type (ADT) Stack ADT Interface
Data Structures Using C++ 2E
Queues.
Stacks Stacks.
Recap: Solution of Last Lecture Activity
Objectives In this lesson, you will learn to: Define stacks
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Stack application: postponing data usage
Visit for more Learning Resources
PART II STACK APPLICATIONS
Queues What is a queue? Queue Implementations: As Array
COMPUTER 2430 Object Oriented Programming and Data Structures I
Stacks Chapter 5 Adapted from Pearson Education, Inc.
Stacks, Queues, and Deques
Lecture 5 Stacks King Fahd University of Petroleum & Minerals
COMPUTER 2430 Object Oriented Programming and Data Structures I
Stacks and Queues 1.
Queue Applications Lecture 31 Mon, Apr 9, 2007.
Queues What is a Queue? Queue Implementations: As Array
Stacks.
Introduction to Stacks
Queue Applications Lecture 31 Tue, Apr 11, 2006.
Introduction to Stacks
Queues What is a queue? Queue Implementations: As Array
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:

1 Introduction to Stacks What is a Stack? Stack implementation using array. Stack implementation using linked list. Applications of Stacks.

2 What is a Stack? A stack is a data structure in which data is added and removed at only one end called the top. To add (push) an item to the stack, it must be placed on the top of the stack. To remove (pop) an item from the stack, it must be removed from the top of the stack too. Thus, the last element that is pushed into the stack, is the first element to be popped out of the stack. i.e., A stack is a Last In First Out (LIFO) data structure

3 An Example of a Stack top Push(8) Push(2) pop()

4 Stack Implementations In our implementations, a stack is a container that extends the AbstractContainer class and implements the Stack interface: We shall study two stack implementations: –StackAsArray The underlying data structure is an array of Object –StackAsLinkedList The underlying data structure is an object of MyLinkedList public interface Stack extends Container { public abstract Object getTop(); public abstract void push(Object obj); public abstract Object pop(); }

5 StackAsArray – Constructor In the StackAsArray implementation that follows, the top of the stack is array[count – 1] and the bottom is array[0]: The constructor’s single parameter, size, specifies the maximum number of items that can be stored in the stack. The variable array is initialized to be an array of length size. public class StackAsArray extends AbstractContainer implements Stack { protected Object[] array; public StackAsArray(int size){ array = new Object[size]; } // …

6 StackAsArray – purge() Method The purpose of the purge method is to remove all the contents of a container. To empty the stack, the purge method simply assigns the value null to the first count positions of the array. public void purge(){ while(count > 0) array[--count] = null; } Complexity is O(…)

7 StackAsArray – push() Method push() method adds an element at the top the stack. It takes as argument an Object to be pushed. It first checks if there is room left in the stack. If no room is left, it throws a ContainerFullException exception. Otherwise, it puts the object into the array, and then increments count variable by one. public void push(Object object){ if (count == array.length) throw new ContainerFullException(); else array[count++] = object; } Complexity is O(…)

8 StackAsArray – pop() Method The pop method removes an item from the stack and returns that item. The pop method first checks if the stack is empty. If the stack is empty, it throws a ContainerEmptyException. Otherwise, it simply decreases count by one and returns the item found at the top of the stack. public Object pop(){ if(count == 0) throw new ContainerEmptyException(); else { Object result = array[--count]; array[count] = null; return result; } Complexity is O(…)

9 StackAsArray – getTop() Method getTop() method is a stack accessor which returns the top item in the stack without removing that item. If the stack is empty, it throws a ContainerEmptyException. Otherwise, it returns the top item found at index count-1. public Object getTop(){ if(count == 0) throw new ContainerEmptyException(); else return array[count – 1]; } Complexity is O(…)

10 StackAsArray – iterator() Method public Iterator iterator() { return new Iterator() { private int index = count-1; public boolean hasNext() { return index >=0; } public Object next () { if(index < 0) throw new NoSuchElementException(); else return array[index--]; } }; }

11 StackAsLinkedList Implementation public class StackAsLinkedList extends AbstractContainer implements Stack { protected MyLinkedList list; public StackAsLinkedList(){ list = new MyLinkedList(); } public void purge(){ list.purge(); count = 0; } // … Complexity is O(…) In the singly-linked list implementation, the top of the stack is the first node in the list.

12 StackAsLinkedList Implementation (Cont’d) public void push(Object obj){ list.prepend(obj); count++; } public Object pop(){ if(count == 0) throw new ContainerEmptyException(); else{ Object obj = list.getFirst(); list.extractFirst(); count--; return obj; } public Object getTop(){ if(count == 0) throw new ContainerEmptyException(); else return list.getFirst(); } Complexity is O(…)

13 StackAsLinkedList Implementation (Cont’d) public Iterator iterator() { return new Iterator() { private MyLinkedList.Element position = list.getHead(); public boolean hasNext() { return position != null; } public Object next() { if(position == null) throw new NoSuchElementException(); else { Object obj = position.getData(); position = position.getNext(); return obj; } }; }

14 Applications of Stacks Some direct applications: –Conversion of tail-recursive algorithms to iterative ones. [Note: Tail recursion will be covered in a later lesson] –Keeping track of method calls: Method activation records are saved on the run-time stack –Evaluation of arithmetic expressions by compilers [infix to postfix conversion, infix to prefix conversion, evaluation of postfix expressions] Some indirect applications –Auxiliary data structure for some algorithms Example: Converting a decimal number to another base –Component of other data structures Example: In this course we will use a stack to implement a Tree iterator

15 Application of Stacks - Evaluating Postfix Expressions (5+9)*2+6*5 An ordinary arithmetical expression like the above is called infix- expression -- binary operators appear in between their operands. The order of operations evaluation is determined by the precedence rules and parentheses. When an evaluation order is desired that is different from that provided by the precedence, parentheses are used to override precedence rules.

16 Application of Stacks - Evaluating Postfix Expressions (Cont’d) Expressions can also be represented using postfix notation - where an operator comes after its two operands or prefix notation – where an operator comes before its two operands. The advantage of postfix and prefix notations is that the order of operation evaluation is unique without the need for precedence rules or parentheses. Prefix (Polish) NotationPostfix (Reverse Polish) NotationInfix Notation / /16 / 2 * *(2 + 14)* 5 + * * * 5 * *(6 – 2) * (5 + 4)

17 Infix to Postfix conversion (manual) An Infix to Postfix manual conversion algorithm is: 1. Completely parenthesize the infix expression according to order of priority you want. 2. Move each operator to its corresponding right parenthesis. 3.Remove all parentheses. Examples: * 5(3 + (4 * 5) )3 4 5 * + a / b ^ c – d * e – a * c ^ 3 ^ 4 a b c ^ / d e * a c 3 4 ^ ^ * - - ((a / (b ^ c)) – ((d * e) – (a * (c ^ (3 ^ 4) ) ) ) )

18 Infix to Prefix conversion (manual) An Infix to Prefix manual conversion algorithm is: 1. Completely parenthesize the infix expression according to order of priority you want. 2. Move each operator to its corresponding left parenthesis. 3.Remove all parentheses. Examples: * 5(3 + (4 * 5) )+ 3 * 4 5 a / b ^ c – d * e – a * c ^ 3 ^ 4 - / a ^ b c - * d e * a ^ c ^ 3 4 ( (a / (b ^ c)) – ( (d * e) – (a * (c ^ (3 ^ 4) ) ) ) )

19 Application of Stacks - Evaluating Postfix Expression (Cont’d) The following algorithm uses a stack to evaluate a postfix expressions. Start with an empty stack for (each item in the expression) { if (the item is an operand) Push the operand onto the stack else if (the item is an operator operatorX){ Pop operand1 from the stack Pop operand2 from the stack result = operand2 operatorX operand1 Push the result onto the stack } Pop the only operand from the stack: this is the result of the evaluation

20 Application of Stacks - Evaluating Postfix Expression (Cont’d) Example: Consider the postfix expression, /, which is (2 + 10) / (9 - 6) in infix, the result of which is 12 / 3 = 4. The following is a trace of the postfix evaluation algorithm for the postfix expression:

21 Application of Stacks – Infix to Postfix Conversion postfixString = “”; while(infixString has tokens){ Get next token x; if(x is operand) Append x to postfixString; else if(x is ‘(’ ) stack.push(x); else if(x is ‘)’ ){ y = stack.pop(); while(y is not ‘(’ ){ Append y to postfixString; y = stack.pop(); } discard both ‘(‘ and ‘)’; } else if(x is operator){ while(stack is not empty){ y = stack.getTop(); // top value is not removed from stack if(y is ‘(‘ ) break; if(y has low precedence than x) break; if(y is right associative with equal precedence to x) break; y = stack.pop(); Append y to postfixString; } push x; }

22 Application of Stacks – Infix to Postfix Conversion (cont’d) while(stack is not empty){ y = stack.pop( ); Append y to postfixString; } step1:step2: step3:step4:

23 Application of Stacks – Infix to Postfix Conversion (cont’d) step5:step6: step7:step8:

24 Application of Stacks – Infix to Postfix Conversion (cont’d) step9:step10: step11: step12:

25 Application of Stacks – Infix to Postfix Conversion (cont’d) step13:step14: step15:step16:

26 Application of Stacks – Infix to Postfix Conversion (cont’d) step17:step18:

27 Application of Stacks – Infix to Prefix Conversion An infix to prefix conversion algorithm: 1.Reverse the infix string 2. Perform the infix to postfix algorithm on the reversed string 3.Reverse the output postfix string Example: (A + B) * (B – C) (C – B) * (B + A) C B - B A + * * + A B - B C reverse Infix to postfix algorithm reverse