CMPT 225 Stacks.

Slides:



Advertisements
Similar presentations
CS Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.
Advertisements

Stacks, Queues, and Linked Lists
Sample PMT online… Browse 1120/sumII05/PMT/2004_1/ 1120/sumII05/PMT/2004_1/
Stacks Chapter 11.
COSC 2006 Chapter 7 Stacks III
COMPSCI 105 S Principles of Computer Science 13 Stacks.
CS Data Structures II Review COSC 2006 April 14, 2017
Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Chapter 6 Stacks. © 2005 Pearson Addison-Wesley. All rights reserved6-2 ADT Stack Figure 6.1 Stack of cafeteria dishes A stack –Last-in, first-out (LIFO)
CMPT 225 Stacks-part2.
Stacks A stack is a data structure that only allows items to be inserted and removed at one end We call this end the top of the stack The other end is.
Chapter 3 Stacks.
© 2006 Pearson Addison-Wesley. All rights reserved7 B-1 Chapter 7 (continued) Stacks.
© 2006 Pearson Addison-Wesley. All rights reserved7A-1 Chapter 7 Stacks.
1 CSCD 326 Data Structures I Stacks. 2 Data Type Stack Most basic property: last item in (most recently inserted) is first item out LIFO - last in first.
Stacks Chapter Chapter Contents Specifications of the ADT Stack Using a Stack to Process Algebraic Expressions Checking for Balanced Parentheses,
Chapter 6 Stacks. © 2005 Pearson Addison-Wesley. All rights reserved6-2 ADT Stack Figure 6.1 Stack of cafeteria dishes A stack –Last-in, first-out (LIFO)
Stack: Linked List Implementation Push and pop at the head of the list New nodes should be inserted at the front of the list, so that they become the top.
Chapter 6 Stacks. © 2005 Pearson Addison-Wesley. All rights reserved6-2 The Abstract Data Type Specifications of an abstract data type for a particular.
Stacks Chapter 6 Data Structures and Problem Solving with C++: Walls and Mirrors, Frank Carrano, © 2012.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 6: Stacks Data Abstraction & Problem Solving with C++
© 2006 Pearson Addison-Wesley. All rights reserved7A-1 Chapter 7 Stacks.
© 2006 Pearson Addison-Wesley. All rights reserved7A-1 Chapter 7 Stacks (and a bit of generics for flavor)
Topic 3 The Stack ADT.
Chapter 7 Stacks II CS Data Structures I COSC 2006
Chapter 6 Stacks CS Data Structures Mehmet H Gunes Modified from authors’ slides.
Data Structures and Algorithms
Review 1 Introduction Representation of Linear Array In Memory Operations on linear Arrays Traverse Insert Delete Example.
Chapter 7 Stacks I CS Data Structures I COSC 2006 April 22, 2017
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.
Chapter 7 Stacks. © 2004 Pearson Addison-Wesley. All rights reserved 7-2 The Abstract Data Type: Developing an ADT During the Design of a Solution Specifications.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,
30 May Stacks (5.1) CSE 2011 Winter Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 6: Stacks Data Abstraction & Problem Solving with C++
Chapter 6 B Stacks. © 2004 Pearson Addison-Wesley. All rights reserved6 B-2 Comparing Implementations All of the three implementations are ultimately.
Data Structures & Algorithms
CHP-3 STACKS.
Stacks & Queues. Introduction to Stacks and Queues Widely used data structures Ordered List of element Easy to implement Easy to use.
CSC 205 – Java Programming II Lecture 30 April 3, 2002.
11/07/141 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: –Data stored –Operations on the.
11/07/141 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: –Data stored –Operations on the.
6/12/20161 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: –Data stored –Operations on the.
Applications of Stack Maitrayee Mukerji. Stacks Last In First Out (LIFO List) ◦ FILO? Insertions and Deletions from the same end called the Top Push(),
Stacks The Stack ADT stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) scheme. The last item placed.
Chapter 7 Stacks © 2006 Pearson Addison-Wesley. All rights reserved 7A-1.
Chapter 6 A Stacks. © 2004 Pearson Addison-Wesley. All rights reserved6 A-2 The Abstract Data Type: Developing an ADT During the Design of a Solution.
Data Abstraction and Problem Solving with JAVA Walls and Mirrors Frank M. Carrano and Janet J. Prichard © 2001 Addison Wesley Data Abstraction and Problem.
Abstract Data Types (ADTs)
CS Data Structures Chapter 6 Stacks Mehmet H Gunes
CENG 213 Data Structures Stacks 5/15/2018 CENG 213.
Stacks Chapter 6.
CC 215 Data Structures Stack ADT
Abstract Data Types (ADTs)
Cinda Heeren / Geoffrey Tien
Stacks.
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Stack.
Introduction to Data Structures
Chapter 6 Stacks.
Stacks Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
CSC 205 – Java Programming II
Stacks Chapter 5 Adapted from Pearson Education, Inc.
Stacks Chapter 6 Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
Stacks and Queues 1.
Abstract Data Types (ADTs)
Ch. 7 Stack 도입을 위한 예 “←” in keyboard input line
Chapters 6 and 7 Stacks.
Chapter 7 (continued) © 2011 Pearson Addison-Wesley. All rights reserved.
Chapter 7 © 2011 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

CMPT 225 Stacks

Stacks A stack is a data structure that only allows items to be inserted and removed at one end We call this end the top of the stack The other end is called the bottom Access to other items in the stack is not allowed A LIFO (Last In First Out) data structure

Using a Stack

What Are Stacks Used For? Most programming languages use a “call stack” to implement function calling When a method is called, its line number and other useful information are pushed (inserted) on the call stack When a method ends, it is popped (removed) from the call stack and execution restarts at the indicated line number in the method that is now at the top of the stack

The Call Stack This is a display of the call stack (from the Eclipse Debug window) Top of the stack: most recently called method. Bottom of the stack: least recently called method

Call Stacks and Recursion A call stack is what makes recursion possible Stacks are also important when traversing tree data structures They enable us to “backtrack” through the tree We’ll see more about this later in the course

Developing and ADT during the design of a solution. Suppose you want to write an editor program that allows the user to correct his/her mistakes using a backspace. Each backspace erases the previous. E.g If you type: abcc ddde ef fg The corrected input is: abcdefg

You need to store the input date in an ADT A first attempt to solve the editor problem: while(not end of the line){ Read a new character ch if(ch is not a <- ) add ch to the ADT else remove from the ADT the item added most recently }

ab <- b <- <- a a a b a b <- a b a b a <- <- a a

There will be a problem if you type a backspace when the ADT is empty A revised solution. while(not end of the line){ Read a new character ch if(ch is not a <- ) add ch to the ADT else if (ADT is not empty) remove from the ADT the item added most recently else ignore the <- }

This ADT is known as a Stack. The solution to the editor problem suggests that the ADT should implement the following operations: Add a new item to ADT Remove from the ADT the last placed item. Check whether the ADT is empty. This ADT is known as a Stack.

Stack Operations A stack should implement (at least) these operations: push – insert an item at the top of the stack pop – remove and return the top item peek – return the top item (without removing it) isEmpty – returns true when the stack is empty These operations should be performed efficiently – in O(1) time

Stack analogy A stack Last-in, first-out (LIFO) property The last item placed on the stack will be the first item removed Analogy A stack of dishes in a cafeteria A queue on the other hand is a FIFO (First in, first out) structure The first item added is the first item to be removed Figure 7-1 Stack of cafeteria dishes

Stack Implementation The stack ADT can be implemented using a variety of data structures. We will look at two: Arrays Linked Lists Both implementations must implement all the stack operations

Stack: Array Implementation If an array is used to implement a stack what is a good index for the top item? Is it position 0? Is it position n-1? Note that push and pop must both work in O(1) time as stacks are usually assumed to be extremely fast The index of the top of the stack is the number of items in the stack - 1 O(n) to insert or remove O(1) to insert or remove

Array Stack Example index of top is current size – 1 6 1 7 8 //Java Code Stack st = new Stack(); st.push(6); //top = 0 st.push(1); //top = 1 st.push(7); //top = 2 st.push(8); //top = 3 top 6 1 7 8 1 2 3 4 5

Array Stack Example index of top is current size – 1 6 1 7 //Java Code Stack st = new Stack(); st.push(6); //top = 0 st.push(1); //top = 1 st.push(7); //top = 2 st.push(8); //top = 3 st.pop(); //top = 2 top 6 1 7 1 2 3 4 5

public class StackArrayBased implements StackInterface { final int MAX_STACK = 50; // maximum size of stack private Object items[]; private int top; //indicates the index of the top element public StackArrayBased() { items = new Object[MAX_STACK]; top = -1; } public boolean isEmpty() { return top < 0; public boolean isFull() { return top == MAX_STACK-1;

public void push(Object newItem) throws StackException { if (!isFull()) { items[++top] = newItem; } else { throw new StackException("StackException on " + "push: stack full"); public Object pop() throws StackException { if (!isEmpty()) { return items[top--]; throw new StackException("StackException on " + "pop: stack empty"); public Object peek() throws StackException { return items[top]; throw new StackException("Stack exception on " + "peek - stack empty");

Array Implementation Summary Easy to implement a stack with an array push and pop can be performed in O(1) time But the implementation is subject to the limitation of arrays that the size must be initially specified because The array size must be known when the array is created and is fixed, so that the right amount of memory can be reserved Once the array is full no new items can be inserted If the maximum size of the stack is not known (or is much larger than the expected size) a dynamic array can be used But occasionally push will take O(n) time

Stack: Linked List Implementation Push and pop at the head of the list New nodes should be inserted at the front of the list, so that they become the top of the stack Nodes are removed from the front (top) of the list Straight-forward linked list implementation push and pop can be implemented fairly easily, e.g. assuming that top is a reference to the node at the front of the list public void push(int x){ // Make a new node whose next reference is // the existing list Node newNode = new Node(x, top); top = newNode; // top points to new node } public int pop(){ if(!isEmpty()){ Node temp=top; top=top.getNext(); // top points to the next node return temp.getItem();

List Stack Example Java Code Stack st = new Stack(); st.push(6); top 6

List Stack Example top 1 6 Java Code Stack st = new Stack(); st.push(6); st.push(1); top 1 6

List Stack Example 7 top 1 6 Java Code Stack st = new Stack(); st.push(6); st.push(1); st.push(7); 7 top 1 6

List Stack Example 8 7 top 1 6 Java Code Stack st = new Stack(); st.push(6); st.push(1); st.push(7); st.push(8); 8 7 top 1 6

List Stack Example 8 7 top 1 6 Java Code Stack st = new Stack(); st.push(6); st.push(1); st.push(7); st.push(8); st.pop(); 8 7 top 1 6

List Stack Example 7 top 1 6 Java Code Stack st = new Stack(); st.push(6); st.push(1); st.push(7); st.push(8); st.pop(); 7 top 1 6

Stack: ADT List Implementation Push() and pop() either at the beginning or at the end of ADT List at the beginning: public void push(Object newItem) { list.add(1, newItem); } // end push public Object pop() { Object temp = list.get(1); list.remove(1); return temp; } // end pop Efficient if ADT List is implemented using Linked List.

Stack: ADT List Implementation Push() and pop() either at the beginning or at the end of ADT List at the end: public void push(Object newItem) { list.add(list.size()+1, newItem); } // end push public Object pop() { Object temp = list.get(list.size()); list.remove(list.size()); return temp; } // end pop Efficient if ADT List is implemented using an array.

Stack: ADT List Implementation Push() and pop() either at the beginning or at the end of ADT List Efficiency depends on implementation of ADT List (not guaranteed) On other hand: it was very fast to implement (code is easy, unlikely that errors were introduced when coding).

Applications of Stacks Call stack (recursion). Searching networks, traversing trees (keeping a track where we are). Examples: Checking balanced expressions Recognizing palindromes Evaluating algebraic expressions

Simple Applications of the ADT Stack: Checking for Balanced Braces A stack can be used to verify whether a program contains balanced braces An example of balanced braces abc{defg{ijk}{l{mn}}op}qr An example of unbalanced braces abc{def}}{ghij{kl}m abc{def}{ghij{kl}m

Checking for Balanced Braces Requirements for balanced braces Each time you encounter a “}”, it matches an already encountered “{” When you reach the end of the string, you have matched each “{” If you process the text from left to right, each time you see a “}” it must be matched with the last seen “{“. This suggests that a stack is an appropriate ADT for solving the problem.

Checking for Balanced Braces Figure 7-3 Traces of the algorithm that checks for balanced braces

A solution for balanced braces using the stack. aStack.createStack(); balancedSoFar = true; while (balancedSoFar and not at the of the string){ ch=read next character; if (ch == ‘{‘) aStack.push(‘{‘); else if (ch == ‘}’) if (!aStack.isEmpty()) aStack.pop(); else balancedSoFar = false; } if (balancedSoFar and aStack.isEmpty()) string has balanced braces the string does not have balanced braces.

Algebraic operations. The algebraic expressions you learned about in school are called infix expressions The term infix indicates that every binary operator appears between its operands. a+b , a+b*c This convention necessitates associatively rules, precedence rules, and the use of parenthesis to avoid ambiguity. a+b*c => (a+b)*c or a + b*c //precedence rule a/b*c => (a/b)* c or a/(b*c) //associatively rule. Two alternative to the traditional infix convention Postfix ab + Prefix +ab

Prefix and Postfix Prefix Postfix The operator appears before the operands. a+(b*c) => a+(*bc) => +a*bc (a+b)*c => (+ab)*c => *+abc Postfix a+(b*c) => a+(bc*) => abc*+ (a+b)*c => (ab+)*c => ab+c* The prefix and postfix convention do not need associatively rules, precedence rules, and the use of parenthesis.

Evaluating Postfix Expressions A postfix calculator Requires you to enter postfix expressions Example: 2 3 4 + * An operator in a postfix expr applies to two operands that immediately precede it. This suggests that stack is an appropriate ADT to solve this problem. When an operand is entered, the calculator Pushes it onto a stack When an operator is entered, the calculator Applies it to the top two operands of the stack Pops the operands from the stack Pushes the result of the operation on the stack

Evaluating Postfix Expressions Figure 7-8 The action of a postfix calculator when evaluating the expression 2 * (3 + 4)

Evaluating Postfix Expressions To evaluate a postfix expression which is entered as a string of characters Simplifying assumptions The string is a syntactically correct postfix expression No unary operators are present No exponentiation operators are present Operands are single lowercase letters that represent integer values

Evaluating Postfix Expressions Pseudo code: int evaluate(String expression) { Stack stack=new Stack(); // creaty empty stack while (true) { String c=expression.getNextItem(); if (c==ENDOFLINE) return stack.pop(); if (c is operand) stack.push(c); else { // operation int operand2=stack.pop(); int operand1=stack.pop(); stack.push(execute(c,operand1,operand2)); }