Queues. Data structures that wait their turn. queues 1

Size: px
Start display at page:

Download "Queues. Data structures that wait their turn. queues 1"

Transcription

1 Queues Data structures that wait their turn queues 1

2 Queue characteristics FIFO: first in, first out insertion of items occurs at one end, removal occurs at the other end first item inserted is the first item removed; second inserted is second removed, third is third, etc. queues 2

3 Queue characteristics Structure is very similar to stack, with much the same considerations -- still subject to overflow and underflow Unlike stack, queue is accessible at both ends Entry and removal still occur at one end -- but each operation occurs at a different end queues 3

4 Java s Queue interface Unlike the Stack ADT, the Java API doesn t provide a full implementation of a generic Queue The Queue interface specifies methods for working with a queue, most of which are listed on the next slide There are several API classes that implement the interface, but each of these adds methods not specified by the interface queues 4

5 Queue ADT member methods Constructor(s) Modifiers enqueue (insert item at back): add dequeue (remove item at front): remove Observers size isempty queues 5

6 Queue implementations The API classes that implement the Queue interface are designed for more sophisticated uses than the simple interface implies We can implement a simple queue using either an array or a linked list as the basic structure queues 6

7 Array implementation public class ArrayQueue<E> implements Cloneable { private Object [ ] data; private int manyitems; private int front; private int rear; queues 7

8 Array implementation public ArrayQueue( ) { final int INITIAL_CAPACITY = 10; manyitems = 0; data = new Object[INITIAL_CAPACITY]; // Since queue is empty, front and rear values // don t matter queues 8

9 Array implementation public ArrayQueue(int initialcapacity) { if (initialcapacity < 0) throw new IllegalArgumentException ("initialcapacity is negative: " + initialcapacity); manyitems = 0; data = new Object[initialCapacity]; queues 9

10 Array implementation public ArrayQueue<E> clone( ) { ArrayQueue<E> answer; try { answer = (ArrayQueue<E>) super.clone( ); catch (CloneNotSupportedException e) { throw new RuntimeException ("This class does not implement Cloneable"); answer.data = data.clone( ); return answer; queues 10

11 Enqueue and dequeue not as simple as they look! // first attempt at enqueue public void add (E item) { if (manyitems == 0) { front = 0; rear = 0; else rear++; data[rear]=item; manyitems++; queues 11

12 dequeue (first attempt) public E remove( ) { E answer; if (manyitems == 0) throw new NoSuchElementException("Queue underflow"); answer = (E)data[front]; front++; manyitems--; return answer; queues 12

13 Problems!!! Consider a queue with a capacity of 3: As items are added, rear approaches capacity: As items are removed, front approaches back: Situation: queue isn t full (manyitems = 0) but attempt to add an item will go beyond array boundary queues 13

14 Possible solution Maintain fixed front of queue: // dequeue method: answer = (E)data[0]; for (int x=0; x<rear; x++) data[x]=data[x+1]; Increases complexity of algorithm considerably -- we ve gone from O(1) operation in original function to O(N) queues 14

15 Better solution: circular array Let front continue to float, but add ability for rear to float as well When rear reaches index capacity-1, if queue isn t full, rear=0 In effect, the successor of the last array index is the first array index -- array can be thought of as circular Can also grow array as necessary queues 15

16 Circular queue implementation Add helper function nextindex as private method of queue class: private int nextindex(int i) { if (++i == data.length) return 0; else return i; Call method from enqueue and dequeue queues 16

17 New enqueue method public void add(e item) { if (manyitems == data.length) ensurecapacity(manyitems*2 + 1); if (manyitems == 0) { front = 0; rear = 0; else rear = nextindex(rear); data[rear] = item; manyitems++; queues 17

18 New dequeue method public E remove( ) { E answer; if (manyitems == 0) throw new NoSuchElementException("Queue underflow"); answer = (E)data[front]; front = nextindex(front); manyitems--; return answer; queues 18

19 Other methods Besides the queue-specific methods (and clone()), the ArrayQueue implementation includes a few other methods: ensurecapacity getcapacity isempty queues 19

20 Invariant for revised queue Number of items on queue stored in variable manyitems Items are stored in circular array from data[front] to data[rear] If queue is empty, manyitems == 0 and the values of front and rear are undefined queues 20

21 Queue as linked list Implementation using linked list is actually easier Need to decide which end of list is which; easiest implementation is to have the head pointer point to the front of the list, and maintain another pointer to keep track of the back queues 21

22 Queue as Linked List Implementation seen here is based on Node<E> class from text; could be even simpler if LinkedListWithNode implementation was chosen Ironically, the Java API s LinkedList class implements the Queue interface, and will be our preferred implementation when we look at queue applications queues

23 Code for linked list queue public class LinkedQueue<E> implements Cloneable{ private int manynodes; private Node<E> front; private Node<E> rear; public LinkedQueue( ) { front = null; rear = null; manynodes = 0; queues 23

24 Code for linked list queue public void add(e item) { if (isempty( )) { front = new Node<E>(item, null); rear = front; else { rear.addnodeafter(item); rear = rear.getlink( ); manynodes++; queues 24

25 Code for linked list queue public LinkedQueue<E> clone( ) { LinkedQueue<E> answer; Node<E>[ ] cloneinfo; try { answer = (LinkedQueue<E>) super.clone( ); catch (CloneNotSupportedException e) { throw new RuntimeException ("This class does not implement Cloneable"); queues 25

26 Clone method continued cloneinfo = Node.listCopyWithTail(front); answer.front = cloneinfo[0]; answer.rear = cloneinfo[1]; return answer; queues 26

27 Code for linked list queue public boolean isempty( ) { return (manynodes == 0); public int size( ) { return manynodes; queues 27

28 Code for linked list queue public E remove( ) { E answer; if (manynodes == 0) throw new NoSuchElementException("Queue underflow"); answer = front.getdata( ); front = front.getlink( ); manynodes--; if (manynodes == 0) rear = null; return answer; queues 28

29 Invariant for linked list implementation The number of items in the queue is stored in the instance variable manynodes. The items in the queue are stored in a linked list, with the front of the queue stored at the head node, and the rear of the queue at the final node. For a non-empty queue, the instance variable front is the head reference of the linked list and the instance variable rear is the tail reference. For an empty queue, both front and rear are the null reference. queues 29

30 Priority Queues Variation on an ordinary queue -- stores entries and a priority value for each entry Elements are dequeued according to priority, highest first In case of a tie, priority queue reverts to FIFO behavior queues2 30

31 PQ implementation One strategy is to create an array of ordinary queues each element in the array would be a queue of items all items in any given queue have equal priority Array index indicates priority level queues2 31

32 PQ Implementation public class PQ<E> { private Queue[] queues; // API Queue interface public int highest; public int total; public int highcurrent; public PQ (int h) { // LinkedList implements Queue highest = h; queues = new LinkedList[h+1]; for (int x=0; x<h+1; x++) { queues[x] = new LinkedList(); total = 0; highcurrent = 0; queues2 32

33 PQ implementation public int size () { return total; public boolean is_empty() { return (total == 0); queues2 33

34 Enqueue method public void PQenqueue(E entry, int priority){ assert (priority <= highest); // check if highest priority entry so far: if (priority > highcurrent) highcurrent = priority; // place entry in queue: queues[priority].add(entry); // increment count of total entries: total++; queues2 34

35 Dequeue method public E PQdequeue(){ assert (size() > 0); int p = highcurrent; total--; for(; p>=0; p--) if (!queues[p].isempty()){ highcurrent = p; return(e)(queues[p].remove()); return (E)(queues[p].remove()); queues2 35

36 Queue Applications

37 Palindrome recognition Palindrome: collection of characters that reads the same backwards and forwards Examples: otto is a palindrome is a palindrome snub no man; nice cinnamon buns! is a palindrome, if you ignore spaces and punctuation queues2 37

38 Palindrome recognition program Read string, storing each character in both a stack and a queue Once string is read, pop stack and dequeue queue, comparing characters if all characters have matched when both structures are empty, you ve got a palindrome queues2 38

39 Palindrome recognition program import java.util.linkedlist; // implements Queue interface import java.util.queue; import java.util.stack; import java.util.scanner; public class Palindrome { queues2 39

40 Palindrome recognition program public static void main(string[ ] args) { Scanner stdin = new Scanner(System.in); String line; do { System.out.print("Your expression (or return to end): "); line = stdin.nextline( ); if (is_palindrome(line)) System.out.println("That is a palindrome."); else System.out.println("That is not a palindrome."); while (line.length( )!= 0); queues2 40

41 Palindrome recognition program public static boolean is_palindrome(string input) { Queue<Character> q = new LinkedList<Character>( ); Stack<Character> s = new Stack<Character>( ); Character letter; int i; for (i = 0; i < input.length( ); i++) { letter = input.charat(i); if (Character.isLetter(letter)) { q.add(letter); s.push(letter); queues2 41

42 Palindrome recognition program while (!q.isempty( )) { if (q.remove( )!= s.pop( )) return false; return true; // end of method // end of class queues2 42

43 Using queues for simulation Many real-world situations can be simulated by employing a queue or queues to represent clients waiting for service Clients might be cars at a traffic light, customers at a grocery store, jobs awaiting CPU time in a computer, etc. Clients are represented by number indicating time of entry into the queue queues2 43

44 Queue simulation program Inputs: amount of time needed to serve one client probability of customer arriving at any given time length of simulation Outputs: number of clients served during simulation average time spent waiting in line queues2 44

45 Queue simulation program: required data structures Queue of clients -- represented by time stamp (second when user entered queue) Server -- an object that simulates the service to be performed -- includes: start( ) method reduceremainingtime( ) method isbusy( ) method variables secondsforservice, timeleft constructor that establishes variable values queues2 45

46 Queue simulation program: required data structures ClientGenerator: reports whether or not a client has arrived in a given second, using probability input to determine odds of arrival Averager: tracks total number of customers served and average time spent waiting in queue queues2 46

47 Simulation: main method import java.util.*; public class CarWash { public static void main(string[ ] args) { final int WASHTIME = 240; final double ARRIVALPROB = ; final int TOTALTIME = 6000; carwashsimulate(washtime, ARRIVALPROB, TOTALTIME); queues2 47

48 Simulation: carwashsimulate() public static void carwashsimulate (int washtime, double arrivalprob, int totaltime) { Queue<Integer> arrivaltimes = new LinkedList<Integer>( ); int next; ClientGenerator arrival = new ClientGenerator(arrivalProb); Server machine = new Server(washTime); Averager waittimes = new Averager( ); int currentsecond; System.out.println("Seconds to wash one car: " + washtime); System.out.print("Probability of customer arrival during a second: "); System.out.println(arrivalProb); System.out.println("Total simulation seconds: " + totaltime); queues2 48

49 carwashsimulate continued if (washtime <= 0 arrivalprob < 0 arrivalprob > 1 totaltime < 0) throw new IllegalArgumentException("Values out of range"); for (currentsecond = 0; currentsecond < totaltime; currentsecond++) { if (arrival.query( )) arrivaltimes.add(currentsecond); if ((!machine.isbusy( )) && (!arrivaltimes.isempty( ))) { next = arrivaltimes.remove( ); waittimes.addnumber(currentsecond - next); machine.start( ); // end if queues2 49

50 carwashsimulate continued // Subtract one second from the time in the current wash cycle. machine.reduceremainingtime( ); // end of for loop // Write the summary information about the simulation. System.out.println("Customers served: " + waittimes.howmanynumbers( )); if (waittimes.howmanynumbers( ) > 0) System.out.println("Average wait: " + waittimes.average( ) + " sec"); // end method // end class queues2 50

51 Server class public class Server { private int secondsforservice; private int timeleft; public Server(int s) { secondsforservice = s; timeleft =0; queues2 51

52 Server class public boolean isbusy( ) { return (timeleft > 0); public void reduceremainingtime( ) { if (timeleft > 0) timeleft--; queues2 52

53 Server Class public void start( ) { if (timeleft > 0) throw new IllegalStateException ("Server is already busy."); timeleft = secondsforservice; // end class queues2 53

54 ClientGenerator class public class ClientGenerator { private double probability; public ClientGenerator(double p) { if ((p < 0) (1 < p)) throw new IllegalArgumentException ("Illegal p: " + p); probability = p; queues2 54

55 ClientGenerator class public boolean query( ) { return (Math.random( ) < probability); // end class queues2 55

56 Averager class public class Averager { private int count; private double sum; public Averager( ) { count =0; sum = 0; queues2 56

57 Averager class public void addnumber(double value) { if (count == Integer.MAX_VALUE) throw new IllegalStateException ("Too many numbers"); count++; sum += value; queues2 57

58 Averager class public double average( ) { if (count == 0) return Double.NaN; else return sum/count; public int howmanynumbers( ) { return count; // end class queues2 58

Stacks. The unorganized person s data structure. stacks 1

Stacks. The unorganized person s data structure. stacks 1 Stacks The unorganized person s data structure stacks 1 Stack characteristics Entries are ordered in terms of access -- both insertion and removal take place at same spot (top of stack) Specialized type

More information

Stacks. Stacks. Main stack operations. The ADT Stack stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) principle.

Stacks. Stacks. Main stack operations. The ADT Stack stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) principle. Stacks 1 Stacks The ADT Stack stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) principle. 2 Main stack operations Insertion and removal are defined by: push(e): inserts

More information

Stacks and Queues. Introduction to abstract data types (ADTs) Stack ADT. Queue ADT. Time permitting: additional Comparator example

Stacks and Queues. Introduction to abstract data types (ADTs) Stack ADT. Queue ADT. Time permitting: additional Comparator example Stacks and Queues Introduction to abstract data types (ADTs) Stack ADT applications interface for Java Stack ex use: reverse a sequence of values Queue ADT applications interface for Java Queue Time permitting:

More information

CMSC 132, Object-Oriented Programming II Summer Lecture 9:

CMSC 132, Object-Oriented Programming II Summer Lecture 9: CMSC 132, Object-Oriented Programming II Summer 2018 Lecturer: Anwar Mamat Lecture 9: Disclaimer: These notes may be distributed outside this class only with the permission of the Instructor. 9.1 QUEUE

More information

Queue rear tail front head FIFO

Queue rear tail front head FIFO The Queue ADT Objectives Examine queue processing Define a queue abstract data type Demonstrate how a queue can be used to solve problems Examine various queue implementations Compare queue implementations

More information

Queues. Stacks and Queues

Queues. Stacks and Queues Queues Reading: RS Chapter 14 Slides are modified from those provided by Marty Stepp www.buildingjavaprograms.com 1 Stacks and Queues Sometimes a less powerful, but highly optimized collection is useful.

More information

LECTURE OBJECTIVES 6-2

LECTURE OBJECTIVES 6-2 The Queue ADT LECTURE OBJECTIVES Examine queue processing Define a queue abstract data type Demonstrate how a queue can be used to solve problems Examine various queue implementations Compare queue implementations

More information

CSC 1052 Algorithms & Data Structures II: Linked Queues

CSC 1052 Algorithms & Data Structures II: Linked Queues CSC 1052 Algorithms & Data Structures II: Linked Queues Professor Henry Carter Spring 2018 Recap A queue simulates a waiting line, where objects are removed in the same order they are added The primary

More information

1 P age DS & OOPS / UNIT II

1 P age DS & OOPS / UNIT II UNIT II Stacks: Definition operations - applications of stack. Queues: Definition - operations Priority queues - De que Applications of queue. Linked List: Singly Linked List, Doubly Linked List, Circular

More information

CSE 373 Data Structures and Algorithms. Lecture 2: Queues

CSE 373 Data Structures and Algorithms. Lecture 2: Queues CSE 373 Data Structures and Algorithms Lecture 2: Queues Queue ADT queue: A list with the restriction that insertions are done at one end and deletions are done at the other First-In, First-Out ("FIFO

More information

Queues. Data Structures and Design with Java and JUnit Rick Mercer 18-1

Queues. Data Structures and Design with Java and JUnit Rick Mercer 18-1 Queues Data Structures and Design with Java and JUnit Rick Mercer 18-1 A Queue ADT First in first out access A Queue is another name for waiting line Example: Submit jobs to a network printer What gets

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Queues ArrayQueue Marcel Turcotte School of Electrical Engineering and Computer Science Version of March 10, 2014 Abstract These lecture notes are meant to be looked

More information

Introduction to Computing II (ITI 1121) Final Examination

Introduction to Computing II (ITI 1121) Final Examination Introduction to Computing II (ITI 1121) Final Examination Instructor: Marcel Turcotte April 2010, duration: 3 hours Identification Student name: Student number: Signature: Instructions 1. 2. 3. 4. 5. 6.

More information

Keeping Order:! Stacks, Queues, & Deques. Travis W. Peters Dartmouth College - CS 10

Keeping Order:! Stacks, Queues, & Deques. Travis W. Peters Dartmouth College - CS 10 Keeping Order:! Stacks, Queues, & Deques 1 Stacks 2 Stacks A stack is a last in, first out (LIFO) data structure Primary Operations: push() add item to top pop() return the top item and remove it peek()

More information

Your Topic Goes Here Queue

Your Topic Goes Here Queue Your Subtopics Go Here Your Topic Goes Here Queue Compiled By: Kiran Joshi 1 Queue Roadmap. 1. Definition 2. Queue examples 3. Working of Queue 4. Applications 2 Definition * A data structure of ordered

More information

CSE 143 SAMPLE MIDTERM

CSE 143 SAMPLE MIDTERM CSE 143 SAMPLE MIDTERM 1. (5 points) In some methods, you wrote code to check if a certain precondition was held. If the precondition did not hold, then you threw an exception. This leads to robust code

More information

1. Introduction. Lecture Content

1. Introduction. Lecture Content Lecture 6 Queues 1 Lecture Content 1. Introduction 2. Queue Implementation Using Array 3. Queue Implementation Using Singly Linked List 4. Priority Queue 5. Applications of Queue 2 1. Introduction A queue

More information

Stacks and Queues. David Greenstein Monta Vista

Stacks and Queues. David Greenstein Monta Vista Stacks and Queues David Greenstein Monta Vista Stack vs Queue Stacks and queues are used for temporary storage, but in different situations Stacks are Used for handling nested structures: processing directories

More information

Basic Data Structures

Basic Data Structures Basic Data Structures Some Java Preliminaries Generics (aka parametrized types) is a Java mechanism that enables the implementation of collection ADTs that can store any type of data Stack s1

More information

COMP 213 Advanced Object-oriented Programming Lecture 8 The Queue ADT (cont.)

COMP 213 Advanced Object-oriented Programming Lecture 8 The Queue ADT (cont.) COMP 213 Advanced Object-oriented Programming Lecture 8 The Queue ADT (cont.) Recall: The Queue ADT A data structure in which elements enter at one end and are removed from the opposite end is called a

More information

Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue

Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue Queues CSE 2011 Fall 2009 9/28/2009 7:56 AM 1 Queues: FIFO Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue Applications,

More information

Basic Data Structures 1 / 24

Basic Data Structures 1 / 24 Basic Data Structures 1 / 24 Outline 1 Some Java Preliminaries 2 Linked Lists 3 Bags 4 Queues 5 Stacks 6 Performance Characteristics 2 / 24 Some Java Preliminaries Generics (aka parametrized types) is

More information

Data Abstraction and Specification of ADTs

Data Abstraction and Specification of ADTs CITS2200 Data Structures and Algorithms Topic 4 Data Abstraction and Specification of ADTs Example The Reversal Problem and a non-adt solution Data abstraction Specifying ADTs Interfaces javadoc documentation

More information

Data Structures G5029

Data Structures G5029 Data Structures G5029 Lecture 2 Kingsley Sage Room 5C16, Pevensey III khs20@sussex.ac.uk University of Sussex 2006 Lecture 2 Stacks The usual analogy is the stack of plates. A way of buffering a stream

More information

Implementing Dynamic Data Structures

Implementing Dynamic Data Structures Chapter 16 Implementing Dynamic Data Structures Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN:

More information

CSC 273 Data Structures

CSC 273 Data Structures CSC 273 Data Structures Lecture 7 - Queues, Deques, and Priority Queues The ADT Queue A queue is another name for a waiting line Used within operating systems and to simulate real-world events Come into

More information

CSE 143. Lecture 4: Stacks and Queues

CSE 143. Lecture 4: Stacks and Queues CSE 143 Lecture 4: Stacks and Queues Stacks and queues Sometimes it is good to have a collection that is less powerful, but is optimized to perform certain operations very quickly. Today we will examine

More information

CS302 - Data Structures using C++

CS302 - Data Structures using C++ CS302 - Data Structures using C++ Topic: Queues and Priority Queues Kostas Alexis Implementations of the ADT Queue Like stacks, queues can have Array-based or Link-based implementation Can also use implementation

More information

Chapter 2. Stack & Queues. M hiwa ahmad aziz

Chapter 2. Stack & Queues.   M hiwa ahmad aziz . Chapter 2 Stack & Queues www.raparinweb.com M hiwa ahmad aziz 1 Stack A stack structure with a series of data elements that Allows access to only the last item inserted. An item is inserted or removed

More information

Building Java Programs

Building Java Programs Building Java Programs Appendix Q Lecture Q-1: stacks and queues reading: appendix Q 2 Runtime Efficiency (13.2) efficiency: measure of computing resources used by code. can be relative to speed (time),

More information

Queues. Virtuelle Fachhochschule. Prof. Dr. Debora Weber-Wulff

Queues. Virtuelle Fachhochschule. Prof. Dr. Debora Weber-Wulff Queues Virtuelle Fachhochschule Prof. Dr. Debora Weber-Wulff!1 Queues First In, First Out Well-known in socialist society Operations enqueue join the back of the line dequeue remove from the front of the

More information

LIFO : Last In First Out

LIFO : Last In First Out Introduction Stack is an ordered list in which all insertions and deletions are made at one end, called the top. Stack is a data structure that is particularly useful in applications involving reversing.

More information

Queues Fall 2018 Margaret Reid-Miller

Queues Fall 2018 Margaret Reid-Miller Queues 15-121 Fall 2018 Margaret Reid-Miller Today Exam 2 is next Tuesday, October 30 Writing methods various classes that implement Lists. Methods using Lists and Big-O w/ ArrayList or LinkedLists Prove

More information

CMSC 132: Object-Oriented Programming II. Stack and Queue

CMSC 132: Object-Oriented Programming II. Stack and Queue CMSC 132: Object-Oriented Programming II Stack and Queue 1 Stack Allows access to only the last item inserted. An item is inserted or removed from the stack from one end called the top of the stack. This

More information

JAVA NOTES DATA STRUCTURES AND ALGORITHMS

JAVA NOTES DATA STRUCTURES AND ALGORITHMS 79 JAVA NOTES DATA STRUCTURES AND ALGORITHMS Terry Marris July 2001 11 QUEUE IMPLEMENTATION - ARRAYS 11.1 LEARNING OUTCOMES By the end of this lesson the student should be able to describe how an array

More information

Solutions to a few of the review problems:

Solutions to a few of the review problems: Solutions to a few of the review problems: Problem 1 The interface Deque can have array based and linked implementations. Partial versions of implementation classes follow. Supply implementations for the

More information

16-Dec-10. Collections & Data Structures ABSTRACTION VS. IMPLEMENTATION. Abstraction vs. Implementation

16-Dec-10. Collections & Data Structures ABSTRACTION VS. IMPLEMENTATION. Abstraction vs. Implementation Collections & Data Structures Boaz Kantor Introduction to Computer Science IDC Herzliya ABSTRACTION VS. IMPLEMENTATION 2 Abstraction vs. Implementation Data structures provide both abstraction and implementation.

More information

CIS Fall Data Structures Midterm exam 10/16/2012

CIS Fall Data Structures Midterm exam 10/16/2012 CIS 2168 2012 Fall Data Structures Midterm exam 10/16/2012 Name: Problem 1 (30 points) 1. Suppose we have an array implementation of the stack class, with ten items in the stack stored at data[0] through

More information

10/26/2017 CHAPTER 3 & 4. Stacks & Queues. The Collection Framework

10/26/2017 CHAPTER 3 & 4. Stacks & Queues. The Collection Framework CHAPTER 3 & 4 Stacks & Queues The Collection Framework 1 Stack Abstract Data Type A stack is one of the most commonly used data structures in computer science A stack can be compared to a Pez dispenser

More information

CSC 1052 Algorithms & Data Structures II: Queues

CSC 1052 Algorithms & Data Structures II: Queues CSC 1052 Algorithms & Data Structures II: Queues Professor Henry Carter Spring 2018 Recap Recursion solves problems by solving smaller version of the same problem Three components Applicable in a range

More information

Queues. CITS2200 Data Structures and Algorithms. Topic 5

Queues. CITS2200 Data Structures and Algorithms. Topic 5 CITS2200 Data Structures and Algorithms Topic 5 Queues Implementations of the Queue ADT Queue specification Queue interface Block (array) representations of queues Recursive (linked) representations of

More information

CSI33 Data Structures

CSI33 Data Structures Department of Mathematics and Computer Science Bronx Community College Outline Chapter 5: Stacks and 1 Chapter 5: Stacks and Chapter 5: Stacks and A Queue ADT A Container Class for First-In-First-Out Access

More information

Linked Lists. It s all connected

Linked Lists. It s all connected Linked Lists It s all connected Linked list: a data structure used to represent an ordered list Consists of a sequence of nodes A node consists of a data item and a reference to the next node -- the connecting

More information

Stacks and Queues. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

Stacks and Queues. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Stacks and Queues EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG What is a Stack? A stack is a collection of objects. Objects in a stack are inserted and removed according to the

More information

Announcements Queues. Queues

Announcements Queues. Queues Announcements. Queues Queues A queue is consistent with the general concept of a waiting line to buy movie tickets a request to print a document crawling the web to retrieve documents A queue is a linear

More information

Name Section Number. CS210 Exam #2 *** PLEASE TURN OFF ALL CELL PHONES*** Practice

Name Section Number. CS210 Exam #2 *** PLEASE TURN OFF ALL CELL PHONES*** Practice Name Section Number CS210 Exam #2 *** PLEASE TURN OFF ALL CELL PHONES*** Practice All Sections Bob Wilson OPEN BOOK / OPEN NOTES You will have all 90 minutes until the start of the next class period. Spend

More information

CSC 321: Data Structures. Fall 2012

CSC 321: Data Structures. Fall 2012 CSC 321: Data Structures Fall 2012 Lists, stacks & queues Collection classes: List (ArrayList, LinkedList), Set (TreeSet, HashSet), Map (TreeMap, HashMap) ArrayList performance and implementation LinkedList

More information

Introduction to Computing II (ITI 1121) Final Examination

Introduction to Computing II (ITI 1121) Final Examination Université d Ottawa Faculté de génie École de science informatique et de génie électrique University of Ottawa Faculty of Engineering School of Electrical Engineering and Computer Science Introduction

More information

csci 210: Data Structures Stacks and Queues

csci 210: Data Structures Stacks and Queues csci 210: Data Structures Stacks and Queues 1 Summary Topics Stacks and Queues as abstract data types ( ADT) Implementations arrays linked lists Analysis and comparison Applications: searching with stacks

More information

CT 229 Object-Oriented Programming Continued

CT 229 Object-Oriented Programming Continued CT 229 Object-Oriented Programming Continued 24/11/2006 CT229 Summary - Inheritance Inheritance is the ability of a class to use the attributes and methods of another class while adding its own functionality

More information

CSC 321: Data Structures. Fall 2013

CSC 321: Data Structures. Fall 2013 CSC 321: Data Structures Fall 2013 Lists, stacks & queues Collection classes: List (ArrayList, LinkedList), Set (TreeSet, HashSet), Map (TreeMap, HashMap) ArrayList performance and implementation LinkedList

More information

BlockingArrayQueue.java. Page 1

BlockingArrayQueue.java. Page 1 1 //BlockingArrayQueue.java 2 //Template blocking queue class, implemented with emulated circular array. 3 //Programmer: Randy Miller 4 //Last modification: April 13, 2015 5 6 7 8 import java.util.arraylist;

More information

CE204 Data Structures and Algorithms Part 2

CE204 Data Structures and Algorithms Part 2 CE204 Data Structures and Algorithms Part 2 14/01/2018 CE204 Part 2 1 Abstract Data Types 1 An abstract data type is a type that may be specified completely without the use of any programming language.

More information

Advanced Java Concepts Unit 3: Stacks and Queues

Advanced Java Concepts Unit 3: Stacks and Queues Advanced Java Concepts Unit 3: Stacks and Queues Stacks are linear collections in which access is completely restricted to just one end, called the top. Stacks adhere to a last-in, first-out protocol (LIFO).

More information

Data Structures and Algorithms for Engineers

Data Structures and Algorithms for Engineers 04-630 Data Structures and Algorithms for Engineers David Vernon Carnegie Mellon University Africa vernon@cmu.edu www.vernon.eu Data Structures and Algorithms for Engineers 1 Carnegie Mellon University

More information

CH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES

CH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES CH4.2-4.3. ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER

More information

Abstract Data Types. Abstract Data Types

Abstract Data Types. Abstract Data Types Abstract Data Types Wolfgang Schreiner Research Institute for Symbolic Computation (RISC) Johannes Kepler University, Linz, Austria Wolfgang.Schreiner@risc.jku.at http://www.risc.jku.at Wolfgang Schreiner

More information

CSE 331 Midterm Exam 2/13/12

CSE 331 Midterm Exam 2/13/12 Name There are 10 questions worth a total of 100 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. The exam is closed book, closed notes, closed

More information

CSE 143 SAMPLE MIDTERM SOLUTION

CSE 143 SAMPLE MIDTERM SOLUTION CSE 143 SAMPLE MIDTERM SOLUTION 1. (5 points) In some methods, you wrote code to check if a certain precondition was held. If the precondition did not hold, then you threw an exception. This leads to robust

More information

Ashish Gupta, Data JUET, Guna

Ashish Gupta, Data JUET, Guna Introduction In general, Queue is line of person waiting for their turn at some service counter like ticket window at cinema hall, at bus stand or at railway station etc. The person who come first, he/she

More information

Another common linear data structure similar to. new items enter at the back, or rear, of the queue. Queue is an ADT with following properties

Another common linear data structure similar to. new items enter at the back, or rear, of the queue. Queue is an ADT with following properties Queues FIFO queue ADT Examples using queues reading character string in order recognize palindromes Queue implementations LL pointer based List ADT based array based tradeoffs 1 ADT queue operations Create

More information

CSCI 162 Dr. Stephanie Schwartz Fall 2014 Review Questions for Exam 1 ** adapted from Ms. Katz and Dr. Hutchens **

CSCI 162 Dr. Stephanie Schwartz Fall 2014 Review Questions for Exam 1 ** adapted from Ms. Katz and Dr. Hutchens ** CSCI 162 Dr. Stephanie Schwartz Fall 2014 Review Questions for Exam 1 ** adapted from Ms. Katz and Dr. Hutchens ** (answers to select problems) 4. (3 pts) Describe the purpose of the instance variables

More information

CmpSci 187: Programming with Data Structures Spring 2015

CmpSci 187: Programming with Data Structures Spring 2015 CmpSci 187: Programming with Data Structures Spring 2015 Lecture #13, Concurrency, Interference, and Synchronization John Ridgway March 12, 2015 Concurrency and Threads Computers are capable of doing more

More information

How can we improve this? Queues 6. Topological ordering: given a sequence of. should occur prior to b, provide a schedule. Queues 5.

How can we improve this? Queues 6. Topological ordering: given a sequence of. should occur prior to b, provide a schedule. Queues 5. Queues 1 Queues A Queue is a sequential organization of items in which the first element entered is the first removed. They are often referred to as FIFO, which stands for first in first out. Examples:

More information

CSE 331 Midterm Exam Sample Solution 2/13/12

CSE 331 Midterm Exam Sample Solution 2/13/12 Question 1. (14 points) (assertions) Using backwards reasoning, find the weakest precondition for each sequence of statements and postcondition below. Insert appropriate assertions in each blank line.

More information

Collections and Iterators. Collections

Collections and Iterators. Collections Collections and Iterators Based on the notes from David Fernandez-Baca and Steve Kautz Based on The Java Tutorial (http://docs.oracle.com/javase/tutorial/java/) Bryn Mawr College CS206 Intro to Data Structures

More information

CS24 Week 4 Lecture 2

CS24 Week 4 Lecture 2 CS24 Week 4 Lecture 2 Kyle Dewey Overview Linked Lists Stacks Queues Linked Lists Linked Lists Idea: have each chunk (called a node) keep track of both a list element and another chunk Need to keep track

More information

Postfix (and prefix) notation

Postfix (and prefix) notation Postfix (and prefix) notation Also called reverse Polish reversed form of notation devised by mathematician named Jan Łukasiewicz (so really lü-kä-sha-vech notation) Infix notation is: operand operator

More information

Classes, interfaces, & documentation. Review of basic building blocks

Classes, interfaces, & documentation. Review of basic building blocks Classes, interfaces, & documentation Review of basic building blocks Objects Data structures literally, storage containers for data constitute object knowledge or state Operations an object can perform

More information

Week 6. Data structures

Week 6. Data structures 1 2 3 4 5 n Week 6 Data structures 6 7 n 8 General remarks We start considering Part III Data Structures from CLRS. As a first example we consider two special of buffers, namely stacks and queues. Reading

More information

Please note that if you write the mid term in pencil, you will not be allowed to submit a remark request.

Please note that if you write the mid term in pencil, you will not be allowed to submit a remark request. University of Toronto CSC148 Introduction to Computer Science Fall 2001 Mid Term Test Section L5101 Duration: 50 minutes Aids allowed: none Make sure that your examination booklet has 8 pages (including

More information

Hashing. It s not just for breakfast anymore! hashing 1

Hashing. It s not just for breakfast anymore! hashing 1 Hashing It s not just for breakfast anymore! hashing 1 Hashing: the facts Approach that involves both storing and searching for values (search/sort combination) Behavior is linear in the worst case, but

More information

The Stack ADT. Stacks and Queues. Stack: Illustration. What is a Stack? Accessors top size isempty

The Stack ADT. Stacks and Queues. Stack: Illustration. What is a Stack? Accessors top size isempty The Stack ADT Stacks and Queues ADT Data Structure Interface add() remove() find() request result EECS200: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Accessors top Mutators push pop of

More information

infix expressions (review)

infix expressions (review) Outline infix, prefix, and postfix expressions queues queue interface queue applications queue implementation: array queue queue implementation: linked queue application of queues and stacks: data structure

More information

Search EECS /57

Search EECS /57 1/57 Search EECS 4315 www.eecs.yorku.ca/course/4315/ Source: weknowyourdreams.com 2/57 Breadth first search 3/57 import gov.nasa.jpf.search.search; public class BFSearch extends Search {... Constructor

More information

CMPSCI 187: Programming With Data Structures. Lecture #11: Implementing Stacks With Arrays David Mix Barrington 28 September 2012

CMPSCI 187: Programming With Data Structures. Lecture #11: Implementing Stacks With Arrays David Mix Barrington 28 September 2012 CMPSCI 187: Programming With Data Structures Lecture #11: Implementing Stacks With Arrays David Mix Barrington 28 September 2012 Implementing Stacks With Arrays The Idea of the Implementation Data Fields

More information

Collections Chapter 12. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Collections Chapter 12. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Collections Chapter 12 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Scope Introduction to Collections: Collection terminology The Java Collections API Abstract nature of collections

More information

Problem 1: Building and testing your own linked indexed list

Problem 1: Building and testing your own linked indexed list CSCI 200 Lab 8 Implementing a Linked Indexed List In this lab, you will be constructing a linked indexed list. You ll then use your list to build and test a new linked queue implementation. Objectives:

More information

Interfaces & Generics

Interfaces & Generics Interfaces & Generics CSC207 Winter 2018 The Programming Interface The "user" for almost all code is a programmer. That user wants to know:... what kinds of object your class represents... what actions

More information

Class 26: Linked Lists

Class 26: Linked Lists Introduction to Computation and Problem Solving Class 26: Linked Lists Prof. Steven R. Lerman and Dr. V. Judson Harward 2 The Java Collection Classes The java.util package contains implementations of many

More information

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University CS 11 Introduction to Computing II Wayne Snyder Department Boston University Today Object-Oriented Programming Concluded Stacks, Queues, and Priority Queues as Abstract Data Types Reference types: Basic

More information

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. Stacks and Queues. Lecture 11.

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. Stacks and Queues. Lecture 11. Lecture 11 1 More Data Structures In this lecture we will use a linked list to implement two abstract data types (ADT) An ADT provides the interface, or what a data structure does We can then use code

More information

CSC 273 Data Structures

CSC 273 Data Structures CSC 273 Data Structures Lecture 3- Stacks Some familiar stacks What is a stack? Add item on top of stack Remove item that is topmost Last In, First Out LIFO Specifications of the ADT Stack Specifications

More information

DNHI Homework 3 Solutions List, Stacs and Queues

DNHI Homework 3 Solutions List, Stacs and Queues Solutions List, Stacs and Queues Problem 1 Given the IntegerQueue ADT below state the return value and show the content of the, initially empty, queue of Integer objects after each of the following operations.

More information

! A data type for which: ! An ADT may be implemented using various. ! Examples:

! A data type for which: ! An ADT may be implemented using various. ! Examples: Stacks and Queues Unit 6 Chapter 19.1-2,4-5 CS 2308 Fall 2018 Jill Seaman 1 Abstract Data Type A data type for which: - only the properties of the data and the operations to be performed on the data are

More information

[2:3] Linked Lists, Stacks, Queues

[2:3] Linked Lists, Stacks, Queues [2:3] Linked Lists, Stacks, Queues Helpful Knowledge CS308 Abstract data structures vs concrete data types CS250 Memory management (stack) Pointers CS230 Modular Arithmetic !!!!! There s a lot of slides,

More information

Linked List. April 2, 2007 Programming and Data Structure 1

Linked List. April 2, 2007 Programming and Data Structure 1 Linked List April 2, 2007 Programming and Data Structure 1 Introduction head A linked list is a data structure which can change during execution. Successive elements are connected by pointers. Last element

More information

16. Dynamic Data Structures

16. Dynamic Data Structures Data Structures 6. Dynamic Data Structures A data structure is a particular way of organizing data in a computer so that it can be used efficiently Linked lists, Abstract data types stack, queue, Sorted

More information

CS6202 - PROGRAMMING & DATA STRUCTURES I Unit IV Part - A 1. Define Stack. A stack is an ordered list in which all insertions and deletions are made at one end, called the top. It is an abstract data type

More information

Lecture 3: Stacks & Queues

Lecture 3: Stacks & Queues Lecture 3: Stacks & Queues Prakash Gautam https://prakashgautam.com.np/dipit02/ info@prakashgautam.com.np 22 March, 2018 Objectives Definition: Stacks & Queues Operations of Stack & Queues Implementation

More information

A queue is a linear collection whose elements are added on one end and removed from the other

A queue is a linear collection whose elements are added on one end and removed from the other A queue is consistent with the general concept of a waiting line to buy movie tickets a request to print a document crawling the web to retrieve documents Adding an element Removing an element A queue

More information

Lecture 2: Stacks and Queues

Lecture 2: Stacks and Queues Lecture 2: Stacks and Queues CSE 373: Data Structures and Algorithms CSE 373 19 WI - KASEY CHAMPION 1 Warm Up 1. Grab a worksheet 2. Introduce yourself to your neighbors J 3. Discuss the answers 4. Log

More information

Stacks Goodrich, Tamassia, Goldwasser Stacks

Stacks Goodrich, Tamassia, Goldwasser Stacks Presentation for use with the textbook Data Structures and Algorithms in Java, 6 th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Stacks Stacks 1 The Stack ADT The Stack ADT

More information

1.00 Lecture 26. Data Structures: Introduction Stacks. Reading for next time: Big Java: Data Structures

1.00 Lecture 26. Data Structures: Introduction Stacks. Reading for next time: Big Java: Data Structures 1.00 Lecture 26 Data Structures: Introduction Stacks Reading for next time: Big Java: 19.1-19.3 Data Structures Set of primitives used in algorithms, simulations, operating systems, applications to: Store

More information

Priority Queues. 1 Introduction. 2 Naïve Implementations. CSci 335 Software Design and Analysis III Chapter 6 Priority Queues. Prof.

Priority Queues. 1 Introduction. 2 Naïve Implementations. CSci 335 Software Design and Analysis III Chapter 6 Priority Queues. Prof. Priority Queues 1 Introduction Many applications require a special type of queuing in which items are pushed onto the queue by order of arrival, but removed from the queue based on some other priority

More information

More Data Structures (Part 1) Stacks

More Data Structures (Part 1) Stacks More Data Structures (Part 1) Stacks 1 Stack examples of stacks 2 Top of Stack top of the stack 3 Stack Operations classically, stacks only support two operations 1. push 2. pop add to the top of the stack

More information

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage:

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage: Discussion 2C Notes (Week 3, January 21) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs32 Abstraction In Homework 1, you were asked to build a class called Bag. Let

More information

Computer Science 9608 (Notes) Chapter: 4.1 Computational thinking and problem-solving

Computer Science 9608 (Notes) Chapter: 4.1 Computational thinking and problem-solving In Computer Science, an abstract data type (ADT) is a mathematical model for a certain data type or structures. This doesn t mean that the ADTs cannot be programmed. But that we must first understand them

More information

ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 )

ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 ) ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 ) Unit - 2 By: Gurpreet Singh Dean Academics & H.O.D. (C.S.E. / I.T.) Yamuna Institute of Engineering & Technology, Gadholi What is a Stack? A stack is a

More information

Queues. Queue ADT Queue Implementation Priority Queues

Queues. Queue ADT Queue Implementation Priority Queues Queues Queue ADT Queue Implementation Priority Queues Queue A restricted access container that stores a linear collection. Very common for solving problems in computer science that require data to be processed

More information