Queues and Stacks. Atul Prakash Downey: Chapter 15 and 16



Similar documents
Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

QUEUES. Primitive Queue operations. enqueue (q, x): inserts item x at the rear of the queue q

Chapter 3: Restricted Structures Page 1

STACKS,QUEUES, AND LINKED LISTS

DATA STRUCTURE - QUEUE

Programming with Data Structures

This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues Goodrich, Tamassia

Data Structures and Algorithms Stacks and Queues

What is a Stack? Stacks and Queues. Stack Abstract Data Type. Java Interface for Stack ADT. Array-based Implementation

Analysis of a Search Algorithm

Linked Lists Linked Lists, Queues, and Stacks

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

CmpSci 187: Programming with Data Structures Spring 2015

Universidad Carlos III de Madrid

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

Linked Lists, Stacks, Queues, Deques. It s time for a chainge!

St S a t ck a ck nd Qu Q eue 1

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Common Data Structures

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

Sequential Data Structures

\Mankinds's progress is measured by the number of. Elementary data structures such as stacks, queues,

Module 2 Stacks and Queues: Abstract Data Types

CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues. Linda Shapiro Spring 2016

Linear ADTs. Restricted Lists. Stacks, Queues. ES 103: Data Structures and Algorithms 2012 Instructor Dr Atul Gupta

Algorithms and Data Structures

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

Stacks and queues. Algorithms and Data Structures, Fall Rasmus Pagh. Based on slides by Kevin Wayne, Princeton

Data Structures and Algorithms

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

CompSci-61B, Data Structures Final Exam

DATA STRUCTURE - STACK

22c:31 Algorithms. Ch3: Data Structures. Hantao Zhang Computer Science Department

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Data Structures Using C++ 2E. Chapter 5 Linked Lists

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures

PROGRAMMING CONCEPTS AND EMBEDDED PROGRAMMING IN C, C++ and JAVA: Lesson-4: Data Structures: Stacks

Lecture Notes on Stacks & Queues

DATA STRUCTURES USING C

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

Introduction to Data Structures and Algorithms

! stack, queue, priority queue, dictionary, sequence, set e.g., a Stack is a list implements a LIFO policy on additions/deletions.

Algorithms and Data S tructures Structures Stack, Queues, and Applications Applications Ulf Leser

Application of Stacks: Postfix Expressions Calculator (cont d.)

Data Structures UNIT III. Model Question Answer

Basic Data Structures and Algorithms

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

Algorithms and Data Structures

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Data Structures and Algorithm Analysis (CSC317) Intro/Review of Data Structures Focus on dynamic sets

Evolving Data Structures with Genetic Programming

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Cpt S 223. School of EECS, WSU

Chapter 8: Bags and Sets

Big O and Limits Abstract Data Types Data Structure Grand Tour.

List, Stack and Queue. Tom Chao Zhou CSC2100B Data Structures Tutorial 3

Algorithms and Data Structures Written Exam Proposed SOLUTION

PROBLEMS (Cap. 4 - Istruzioni macchina)

Data Structures. Jaehyun Park. CS 97SI Stanford University. June 29, 2015

Algorithms and Abstract Data Types

Data Structures and Algorithms Lists

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

EECE 276 Embedded Systems

Data Structures in the Java API

recursion, O(n), linked lists 6/14

CSE 326, Data Structures. Sample Final Exam. Problem Max Points Score 1 14 (2x7) 2 18 (3x6) Total 92.

Data Structures and Data Manipulation

Stacks. Data Structures and Data Types. Collections

ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION /5:15-6:45 REC-200, EVI-350, RCH-106, HH-139

Introduction to Data Structures

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

3 Abstract Data Types and Search

10CS35: Data Structures Using C

Outline. The Stack ADT Applications of Stacks Array-based implementation Growable array-based stack. Stacks 2

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Data Structures and Algorithms

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

7.1 Our Current Model

Stack Allocation. Run-Time Data Structures. Static Structures

EE2204 DATA STRUCTURES AND ALGORITHM (Common to EEE, EIE & ICE)

Java Collection Framework hierarchy. What is Data Structure? Chapter 20 Lists, Stacks, Queues, and Priority Queues

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION

Java Software Structures

Abstract Data Types. Chapter 2

Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive.

Binary Search Trees CMPSC 122

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010

Chapter Objectives. Chapter 9. Sequential Search. Search Algorithms. Search Algorithms. Binary Search

Sorting revisited. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2)

Transcription:

Queues and Stacks Atul Prakash Downey: Chapter 15 and 16

Queues Queues occur in real life a lot. Queues at checkout Queues in banks In software systems: Queue of requests at a web servers

Properties of Queues Queue is a FIFO data structure. First-infirst-out. Basic operations: enqueue(element): add element to the end of the queue dequeue() -> returns the element from the front of the queue, removing it isempty() -> returns true if queue empty Some queues provide additional operations, such as peeking at the front

Wrapping Lists to Create Queues Can use lists as the underlying structure. Create empty queue boolean Q.isEmpty(): true if queue is empty Q.enqueue(T elem): add element at the end of the list T Q.dequeue(): remove element from the front of the list and returns it.

Design Outline List a; isempty() { if a.size() == 0 return true; else return false; } Queue() { a = new List() } enqueue(t element) { a.add(element); } dequeue() { T result = a.get(0); a.remove(result); return result; }

What we just did List a; T data[]; isempty() { if a.size() == 0 return true; else return false; } enqueue(t element) { a.add(element); } dequeue() { T result = a.get(0); a.remove(result); return result; } Queue.java Queue() { a = new List() } size() {... } add(t element) {... } remove() {... T get(int i) { } List.java

Discussion Lists can do everything that queues can So, why implement a queue class? Why not directly use lists?

Wrapping We created lists by using an array and providing functions such as add(), remove(), get(), size(), etc. We created queues by using lists as the starting point We are sometimes restricting functionality by doing this, but also making the data structure safer and easier to use for the intended task

Queue using ArrayList a (pseudo-code) enqueue(o): same as a.add(o) a.dequeue(): three steps using ArrayList API result = a.get(0) a.remove(0) or a.remove(result), depending on the interface of arraylist a return result

Performance using Array-based Lists enqueue operation: a[size] = element; size++. Performance: O(1) But, if array fills up, expensive. all n elements have to be copied to a new, larger array. Cost: O(n) in copying. Think about if you double every time array fills up, what is the average cost per insertion? Suppose array size is 100. First 100 insertions are cheap (constant time). Next one costs 100 operations. Then, the next 100 will be cheap. Next one costs 200. Then, the next 200 will be cheap, next one costs 400, etc. One expensive operation makes subsequent ones cheap. Average performance per insert is at most one element copy + one element update. It is still constant time.

deque Operation save A[0], shift all elements left, and decrement size Have to shift everything to the left. Cost: O(size)

Overall Cost With array-based lists, adding elements at the end and removing from the front: Enqueue: O(n) worst-case. O(1): average Dequeue: O(n)

Mini-exercise Create a stack by wrapping a list. Three operations: isempty() push(t element): push an element on top of the stack T pop(): remove and return the top element from the stack Just need to give pseudo-code of Stack.java

Discussion Stacks: What is the cost of push and pop() in terms of big-oh? Queues: The cost of dequeue is O(n) and the cost of enqueue is O(1). Can we make them both O(1)?

Making Queues Efficient Yes, we can make both operations O(1) Using arrays with a data structure called circular queues Using linked lists (more on that later)

Circular Queues: Basic Idea Right now, our implementation is as follows: Arrays used to implement lists Lists used to implement queues It turns out that we can implement queues directly on top of arrays more efficiently.

Circular queue Keep a head pointer to the the front of the queue. Tail pointer to the next empty slot. Best to imagine the array to be CIRCULAR. Position 0 follows 17.

Insertion We added 15 to the queue. tail advances. Basic code (without error checking for full queue) A[tail] = elem; tail = (tail + 1) % size.

Deletion head advances on deletion. Basic code without error checking for empty queue: result = A[head]; head = (head + 1) mod size; return result

Wrap around After some deletions and insertions, we can get the above situation. Queue: 4, 5, 8,., 12. Arithmetic on head/tail must be mod 18

Inserts after wraparound Queue: 4, 5, 8, 4 11, 12, 13

Empty Queue What happens when we dequeue the last element from the queue?

Empty queue situation Rule: (head == tail) means the queue is empty. Initialization of a circular queue: head = 0; tail = 0 would be a reasonable choice.

Full Queue What happens on adding to the following queue?

Use the last slot? head will become same as tail. How do we know whether the queue is full or empty?

Note If the queue contains values, we can't really use the values to determine whether the queue is empty or full.

Equivalent queues 10 30 40 There is always some value in "empty" slots in the array.

Avoiding the trap Always leave one slot empty. This is a full circular queue Rule: if (tail + 1) mod size equals head, then the queue is full.

Cost of insertion/ deletion Insertion cost: add at tail, advance tail. O(1). (assuming no overflow allowed). Deletion cost: remove from head, advance head. O(1).

Discussion Circular queues, as described, are of bounded size, limited by array size. What if we wanted unbounded-length queues?