1 Introduction to Computation and Problem Solving Class 23: Introduction to Data Structures: Stacks and Queues Prof. Steven R. Lerman and Dr. V. Judson.

Slides:



Advertisements
Similar presentations
Chapter 25 Lists, Stacks, Queues, and Priority Queues
Advertisements

Chapter 20 Recursion.
CS Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.
1 Introduction to Computation and Problem Solving Class 24: Case Study: Building a Simple Postfix Calculator Prof. Steven R. Lerman and Dr. V. Judson Harward.
Introduction to Computation and Problem
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
10 Copyright © 2005, Oracle. All rights reserved. Reusing Code with Inheritance and Polymorphism.
15 Copyright © 2005, Oracle. All rights reserved. Adding User Interface Components and Event Handling.
Topic 12 The List ADT. 9-2 Objectives Examine list processing and various ordering techniques Define a list abstract data type Examine various list implementations.
Linked List A linked list consists of a number of links, each of which has a reference to the next link. Adding and removing elements in the middle of.
Linked Lists Chapter 4.
1111 Abstract Data Types Cpt S 223. School of EECS, WSU.
Data Structures ADT List
Chapter 24 Lists, Stacks, and Queues
ITEC200 Week04 Lists and the Collection Interface.
AITI Lecture 19 Linked List Adapted from MIT Course 1.00 Spring 2003 Lecture 26 and Tutorial Note 9 (Teachers: Please do not erase the above note)
Data Structures Using C++
1 CompSci 105 SS 2005 Principles of Computer Science Lecture 11: Linked Lists Lecturer: Santokh Singh Assignment 2 due tomorrow, i.e. Friday 21 Jan 2005.
COSC 1P03 Data Structures and Abstraction 10.1 The List If A is success in life, then A equals x plus y plus z. Work is x; y is play; and z is keeping.
Data Structures Part 2 Stacks, Queues, Trees, and Graphs Briana B. Morrison CSE 1302C Spring 2010.
Double-Linked Lists and Circular Lists
FIFO Queues CSE 2320 – Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1.
Chapter 1 Object Oriented Programming 1. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
1 Joe Meehean. Ordered collection of items Not necessarily sorted 0-index (first item is item 0) Abstraction 2 Item 0 Item 1 Item 2 … Item N.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Hash Tables,
Page 1 – Spring 2010Steffen Vissing Andersen Software Development with UML and Java 2 SDJ I2, Spring 2010 Agenda – week 7, 2010 • Pakages • Looking back.
Review Pseudo Code Basic elements of Pseudo code
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
The List ADT Textbook Sections
Object-Oriented Programming. 2 An object, similar to a real-world object, is an entity with certain properties, and with the ability to react in certain.
Lecture Stacks. A stack is a Last-In-First-Out (LIFO) or a First-In-Last-Out (FILO) abstract data type E.g. a deck of cards in which cards may be added.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 7: Recursion Java Software Structures: Designing and Using.
Chapter 9: Data Structures I
Stack & Queues COP 3502.
Topic 16 Sorting Using ADTs to Implement Sorting Algorithms.
Chapter 14 Introduction to Collections
Building Java Programs Chapter 14
Chapter 5.
COSC 1P03 Data Structures and Abstraction 9.1 The Queue Whenever you are asked if you can do a job, tell 'em, "Certainly, I can!" Then get busy and find.
Elementary Data Structures CS 110: Data Structures and Algorithms First Semester,
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 The Stack ADT (§4.2) The Stack ADT stores arbitrary objects Insertions and deletions.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Unit 11 1 Unit 11: Data Structures H We explore some simple techniques for organizing and managing information H This unit focuses on: Abstract Data Types.
Stacks. 2 Outline and Reading The Stack ADT (§2.1.1) Array-based implementation (§2.1.1) Growable array-based stack (§1.5) Java.util.Stack class Java.util.Vector.
Part-B1 Stacks. Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations.
Topic 3 The Stack ADT.
Chapter 3 Introduction to Collections – Stacks Modified
Information and Computer Sciences University of Hawaii, Manoa
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
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.
Stacks and Queues. 2 3 Runtime Efficiency efficiency: measure of computing resources used by code. can be relative to speed (time), memory (space), etc.
CSC 212 – Data Structures Lecture 17: Stacks. Question of the Day Move one matchstick to produce a square.
AITI Lecture 18 Introduction to Data Structure, Stack, and Queue Adapted from MIT Course 1.00 Spring 2003 Lecture 23 and Tutorial Note 8 (Teachers: Please.
90-723: Data Structures and Algorithms for Information Processing Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 1: Introduction Data.
Chapter 4 ADTs Stack and Queue. 4-2 Formal ADT Specifications The Java interface construct lets us collect together method interfaces into a syntactic.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Stack. ADS2 Lecture 1010 The Stack ADT (GoTa §5.1) The Stack ADT stores arbitrary objects Insertions and deletions follow the last-in.
Click to edit Master text styles Stacks Data Structure.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
Elementary Data Structures
Stacks.
Stacks and Queues.
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Building Java Programs
CMSC 341 Lecture 5 Stacks, Queues
Stacks and Queues.
CS210- Lecture 5 Jun 9, 2005 Agenda Queues
Stacks and Queues.
CMPT 225 Lecture 7 – Stack.
Presentation transcript:

1 Introduction to Computation and Problem Solving Class 23: Introduction to Data Structures: Stacks and Queues Prof. Steven R. Lerman and Dr. V. Judson Harward

2 Algorithms An algorithm is a precise but not necessarily formal description of how to solve a class of computational problem. Examples: insertion sort, Newton's method, A data structure is a general method of storing and accessing data that optimizes or organizes one or more aspects of data access, e.g., speed, ordering, etc. Examples, arrays, Vector A pattern is a strategy for solving a problem, specific enough to be recognizable, but general enough so that the programmer will customize it for each case. Examples: next lecture!

3 Data Structures A good example is a queue. We encounter queues all the time in every day life. What makes a queue a queue? What is the essence of queueness?

4 Queues A queue is a data structure to which you add new items at one end and remove old items from the other. Add items here Remove items here

5 Queue Operations Add an item: Add another item: Add a 3 rd item: tail head

6 Queue Operations, 2 Remove an item: Add another item: Remove another item: tail head tail head tail head

7 Queue Interface public interface Queue { public boolean isEmpty(); public void add( Object o ); public Object remove() throws NoSuchElementException; public void clear(); }

8 Abstract vs Concrete Data Types The data structure actually combines two object-oriented concepts: the data structure interface, which defines an abstract data type (ADT), and a particular implementation of that interface that provides a concrete data type (CDT).

9 Uses for Queues Queues are useful in many algorithms and in situations where two systems pass information to each other but will operate more efficiently without handshaking on each information transfer. Queues buffer the information transfer and allow the queue source and destination to process the information at independent rates. The Java® event queue is a good example. Derived types: priority queues, streams

10 The Right Data Structure for the Job Suppose you are writing a graphics editor. You want to implement an unlimited Undo operation. You cleverly design a class that captures each modification you make as an object. You want to use these objects to undo the mods. What data structure do we want? A queue?

11 Stacks Stacks resemble queues except that items are added and removed from the same end. Stacks are sometimes referred to as LIFO queues (last in first out) as opposed to FIFO queues (first in first out) which describe the base queue type. Add and remove items here push on pop off

12 Stack Operations Push 1Push 2Push 3 Push 4 Pop 3 top

13 Uses of Stacks Stacks provide an orderly way to postpone the performance of subsidiary tasks encountered during program execution. They are often associated with recursive algorithms. Derived types: program stacks, parser stacks

14 Stack Interface public interface Stack { public boolean isEmpty(); public void push( Object o ); public Object pop() throws EmptyStackException; public void clear(); }

15 Using a Stack to Reverse an Array public class Reverse { public static void main(String args[]) { int [] array = { 1, 2, 3, 4, 5 }; int i; Stack stack = new ArrayStack(); for ( i = 0; i < array.length; i++ ) stack.push( new Integer( array[ i ] )); i = 0; while ( !stack.isEmpty() ) { array[ i ] = ((Integer) stack.pop()).intValue(); System.out.println( array[ i++ ] ); }

16 Stack Implementation Based on an Array In our array-based implementation, the top of the stack will move down the array as we push items onto it and will move back up as we pop them. The bottom of the stack will always lie at element 0 of the array. In a sense, we are building the stack "upside down" in the array. Array Index First item on stack Current top of stack Last available position

17 ArrayStack, 1 import java.util.*; public class ArrayStack implements Stack { static public final int DEFAULT_CAPACITY = 8; private Object[] stack; private int top = -1; private int capacity; public ArrayStack(int cap) { capacity = cap; stack = new Object[capacity]; } public ArrayStack() { this( DEFAULT_CAPACITY ); }

18 ArrayStack, 2 public boolean isEmpty() { return ( top < 0 ); } public void clear() { for ( int i = 0; i < top; i++ ) stack[ i ] = null; // for garbage collection top = -1; }

19 ArrayStack, 3 public void push(Object o) { if (++top == capacity) grow(); stack[top] = o; } private void grow() { capacity *= 2; Object[] oldStack = stack; stack = new Object[capacity]; System.arraycopy(oldStack, 0, stack, 0, top); }

20 ArrayStack, 4 public Object pop() throws EmptyStackException { if ( isEmpty() ) throw new EmptyStackException(); else { // your code goes here // remove and return item on top of the stack; // adjust private variables; free memory return null; }

21 A Naïve Queue Implementation front of queue rear of queue lastIndex-1 lastIndex capacity-1 lastIndex-1 lastIndex lastIndex+1 capacity-1

22 A Ring Queue Implementation Based on Array Two cases: 1.front < rear 2.rear < front, queue has wrapped round front front+1 rear-1 rear size-1 occupied rear-1 rear front front size-1 occupied

23 Ring Structure of Array-Based Queue end of array start of array start of queue end of array start of array end of queue start of queue end of queue size-1 rear+1 rear rear-1 front+1 front 0 rear-1 size-1 rear+1 rear 0 front+1 front

24 Implementing a Ring Queue Implementing a RingQueue is surprisingly difficult. The trick is to use the concept of invariants. An invariant is a property of a class that is true whenever one of the methods of the class is not executing. While a class method is executing, the class can violate the invariant for a moment, but it must restore it before exiting the method. public class RingQueue implements Queue{ private Object[] queue; private int front; private int rear; private int capacity; private int size = 0;

25 RingQueue Invariants When not executing a static or instance method of RingQueue all the following must hold: queue : holds a reference to the ring array size : Always >=0. Holds the # of items on the queue front : if size>0, holds the index to the next item to be removed from the queue rear : if size>0, holds the index to the last item to be added to the queue capacity : Holds the size of the array referenced by queue

26 Sample RingQueue Methods public boolean isEmpty() { return ( size == 0 ); } public Object remove() { if ( isEmpty() ) throw new NoSuchElementException(); else { Object ret = queue[ front ]; queue[ front ] = null; //for garbage collection front = (front + 1) % capacity; size--; return ret; }

27 Stack Exercise, 1 You will write the pop() method for ArrayStack and write the method in UndoViz that implements Undo. Download Lecture23.zip from the web site. Open it in Winzip and extract it to a new directory; 1.Click the extract button, which will open the extract dialogue. 2.Use the browser on the right to navigate to where you want to locate the new directory. 3.Click "New Folder" and name it. 4.Then click the extract button in the upper right corner of the dialogue. Open a new project in Forte and mount the directory you just created

28 Stack Exercise, 2 Look over ArrayStack.java. The user interface is all contained in UndoViz.java. This contains the main method to run the visualization. You don't need to understand the code in most of the methods. Just note how the undo button calls do_undo() when it is pressed. Compile the project and execute UndoViz. (Right button down and select execute). Confirm that the Undo button does not work. Now complete the pop() method in ArrayStack and the do_undo() method in UndoViz. You shouldn't have to change any other methods. Recompile and check that Undo now works.

29 Stack Exercise, 3 public class UndoViz extends JPanel {... public UndoViz() {... undoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { do_undo(); } });... }... public void do_undo() { // Your code goes here. // Undo the last graphic addition and redraw. }

30 RingQueue Exercise This exercise is more challenging. Don't worry if you can't complete it. Solutions will be posted on the web. You will write the add() method for RingQueue. Build the whole project. Execute RingQueueViz and confirm that the add button doesn't work. Now write the RingQueueadd() method. Make sure that by the time you exit the methods all invariants still hold. What will you do if size == capacity before you add an element? Compile and test by running RingQueueViz. Java® is a trademark or registered trademark of Sun Microsystems, Inc. in the United States and other countries.