Data Structures and Algorithms 2/2561

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
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)
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
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.
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
CHAPTER 7 Queues.
Elementary Data Structures CS 110: Data Structures and Algorithms First Semester,
1 Queues (5.2) CSE 2011 Winter May Announcements York Programming Contest Link also available from.
Queues Ellen Walker CPSC 201 Data Structures Hiram College.
CHAPTER 4 Queues MIDTERM THURSDAY, OCTOBER 17 IN LAB.
Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
COMP 103 Linked Stack and Linked Queue.
© 2006 Pearson Addison-Wesley. All rights reserved8-1 Chapter 8 Queues CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008.
1 Lecture 24 Abstract Data Types (ADT) –I Overview  What is an Abstract Data type?  What is Stack ADT?  Stack ADT Specifications  Array Implementation.
Fall 2007CS 2251 Queues Chapter 6. Fall 2007CS 2252 Chapter Objectives To learn how to represent a waiting line (queue) and how to use the methods in.
CS1020 Data Structures and Algorithms I Lecture Note #9 Stacks and Queues Two basic linear data structures.
1 Lecture 26 Abstract Data Types – IV Overview  The List ADT  Implementing Stacks as Linked List  Linked List Implementation of Queues .  Preview:
Stacks, Queues, and Deques
Stacks, Queues, and Deques
CSE 373 Data Structures and Algorithms Lecture 2: Queues.
Chapter 7 Stacks I CS Data Structures I COSC 2006 April 22, 2017
© 2006 Pearson Addison-Wesley. All rights reserved8 A-1 Chapter 8 Queues (slightly modified by Dan Fleck)
1 Chapter 7 Stacks and Queues. 2 Stack ADT Recall that ADT is abstract data type, a set of data and a set of operations that act upon the data. In a stack,
Chapter Objectives  Learn how to represent a waiting line (queue)  Become proficient using the methods in the Queue  Understand how to implement the.
Chapter 8 Queue I CS Data Structures I COSC2006 April 24, 2017
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
CS 367 Introduction to Data Structures Lecture 5.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
CSE 373: Data Structures and Algorithms Lecture 2: Queues.
Chapter 4 ADTs Stack and Queue. 4-2 Formal ADT Specifications The Java interface construct lets us collect together method interfaces into a syntactic.
Queues By Jimmy M. Lu. Overview Definition Standard Java Queue Operations Implementation Queue at Work References.
CS1020 – Data Structures And Algorithms 1 AY Semester 2
Linked Data Structures
Queues Chapter 8 (continued)
Elementary Data Structures
Data Abstraction & Problem Solving with C++
Processing Sequences of Elements
COSC160: Data Structures: Lists and Queues
Marcus Biel, Software Craftsman
QueueStack CS1020.
CC 215 Data Structures Queue ADT
Csc 2720 Data structure Instructor: Zhuojun Duan
Week 3 - Friday CS221.
Stacks.
CSE 373: Data Structures and Algorithms
Stack and Queue APURBO DATTA.
CS201: Data Structures and Discrete Mathematics I
HW-6 Deadline Extended to April 27th
Queues, Deques and Priority Queues
THURSDAY, OCTOBER 17 IN LAB
Stacks, Queues, and Deques
Queues.
Stacks and Queues.
Lesson Objectives Aims
CSC 143 Queues [Chapter 7].
Queues: Implemented using Arrays
CS210- Lecture 5 Jun 9, 2005 Agenda Queues
Chapter 8 Queues © 2006 Pearson Addison-Wesley. All rights reserved.
Queues Jyh-Shing Roger Jang (張智星)
Chapter 4 Queues.
More Data Structures (Part 1)
Circular Queues: Implemented using Arrays
Queues cont. Chapter 8 © 2011 Pearson Addison-Wesley. All rights reserved.
Stacks, Queues, and Deques
Queues Chapter 8 © 2011 Pearson Addison-Wesley. All rights reserved.
Stacks and Queues.
Queues.
The Queue ADT Definition A queue is a restricted list, where all additions occur at one end, the rear, and all removals occur at the other end, the front.
Presentation transcript:

88621159 Data Structures and Algorithms 2/2561 Queues First-In-First-Out (FIFO) 88621159 Data Structures and Algorithms 2/2561

[CS1020 Lecture 9: Stacks and Queues] 6 Queue ADT: Operations A Queue is a collection of data that is accessed in a first-in-first-out (FIFO) manner Major operations: “poll” (or “dequeue”), “offer” (or “enqueue”), and “peek”. poll() offer(item) Back of queue Front of queue peek() queue [CS1020 Lecture 9: Stacks and Queues]

[CS1020 Lecture 9: Stacks and Queues] 6 Queue ADT: Uses Print queue Simulations Breadth-first traversal of trees Checking palindromes - for illustration only as it is not a real application of queue [CS1020 Lecture 9: Stacks and Queues]

[CS1020 Lecture 9: Stacks and Queues] 6 Queue ADT: Interface import java.util.*; public interface QueueADT <E> { // return true if queue has no elements public boolean isEmpty(); // return the front of the queue public E peek(); // remove and return the front of the queue public E poll(); // also commonly known as dequeue // add item to the back of the queue public boolean offer(E item); // also commonly known as enqueue } QueueADT.java [CS1020 Lecture 9: Stacks and Queues]

[CS1020 Lecture 9: Stacks and Queues] 6 Queue: Usage Queue q = new Queue (); q.offer (“a”); q.offer (“b”); q.offer (“c”); d = q.peek (); q.poll (); q.offer (“e”); q front back d a a b c e [CS1020 Lecture 9: Stacks and Queues]

7 Queue Implementation: Array (1/7) Use an Array with front and back pointer QueueArr arr 1 7 8 9 2 3 4 5 6 A B C D E offer(“F”); F G offer(“G”); back poll(); 10 maxsize front [CS1020 Lecture 9: Stacks and Queues]

7 Queue Implementation: Array (2/7) “Circular”Array needed to recycle space 1 2 3 4 5 6 7 8 9 Given a queue A B C D E F G front back A B C D E F G 1 7 8 9 2 3 4 5 6 front back To advance the indexes, use front = (front+1) % maxsize; back = (back+1) % maxsize; [CS1020 Lecture 9: Stacks and Queues]

7 Queue Implementation: Array (3/7) Question: what does (front == back) mean? A: Full queue B: Empty queue C: Both A and B D: Neither A nor B  [CS1020 Lecture 9: Stacks and Queues]

7 Queue Implementation: Array (4/7) Ambiguous full/empty state Queue Empty State e f c d Queue Full State F B FB size 4 Solution 1 – Maintain queue size or full status Solution 2 (Preferred and used in our codes) – Leave a gap! Don’t need the size field this way Full Case: (((B+1) % maxsize) == F) Empty Case: F == B e c d B F [CS1020 Lecture 9: Stacks and Queues]

7 Queue Implementation: Array (5/7) import java.util.*; // This implementation uses solution 2 to resolve full/empty state class QueueArr <E> implements QueueADT <E> { private E [] arr; private int front, back; private int maxSize; private final int INITSIZE = 1000; public QueueArr() { arr = (E []) new Object[INITSIZE]; // create array of E objects front = 0; // the queue is empty back = 0; maxSize = INITSIZE; } public boolean isEmpty() { return (front == back); // use solution 2 QueueArr.java [CS1020 Lecture 9: Stacks and Queues]

7 Queue Implementation: Array (6/7) public E peek() { // return the front of the queue if (isEmpty()) return null; else return arr[front]; } public E poll() { // remove and return the front of the queue E obj = arr[front]; arr[front] = null; front = (front + 1) % maxSize; // “circular” array return obj; public boolean offer(E o) { // add item to the back of the queue if (((back+1)%maxSize) == front) // array is full if (!enlargeArr()) return false; // no more memory to // enlarge the array arr[back] = o; back = (back + 1) % maxSize; // “circular” array return true; QueueArr.java [CS1020 Lecture 9: Stacks and Queues]

7 Queue Implementation: Array (7/7) private method private boolean enlargeArr() { int newSize = maxSize * 2; E[] x = (E []) new Object[newSize]; if (x == null) // i.e. no memory allocated to array of E objects return false; for (int j=0; j < maxSize; j++) { // copy the front (1st) element, 2nd element, ..., in the // original array to the 1st (index 0), 2nd (index 1), ..., // positions in the enlarged array. Q: Why this way? x[j] = arr[(front+j) % maxSize]; } front = 0; back = maxSize - 1; arr = x; maxSize = newSize; return true; QueueArr.java [CS1020 Lecture 9: Stacks and Queues]

8 Queue Implementn: Linked List (1/4) Method #1 (Composition): Use TailedLinkedList Do not use BasicLinkedList as we would like to use addLast() of TailedLinkedList. QueueLL list TailedLinkedList head num_nodes tail 4 a1 a2 a3 a4 [CS1020 Lecture 9: Stacks and Queues]

8 Queue Implementn: Linked List (2/4) Method #1 (Composition): Use TailedLinkedList import java.util.*; class QueueLL <E> implements QueueADT <E> { private TailedLinkedList <E> list; public QueueLL() { list = new TailedLinkedList <E> (); } public boolean isEmpty() { return list.isEmpty(); } public boolean offer(E o) { list.addLast(o); // isEmpty(), addLast(), getFirst(), removeFirst() // are public methods of TailedLinkedList return true; } public E peek() { if (isEmpty()) return null; return list.getFirst(); public E poll() { E obj = peek(); if (!isEmpty()) list.removeFirst(); return obj; QueueLL.java [CS1020 Lecture 9: Stacks and Queues]

8 Queue Implementn: Linked List (3/4) Method #2 (Inheritance): Extend TailedLinkedList QueueLLE TailedLinkedList head num_nodes tail 4 a1 a2 a3 a4 [CS1020 Lecture 9: Stacks and Queues]

8 Queue Implementn: Linked List (4/4) Method #2 (Inheritance): Extend TailedLinkedList import java.util.*; class QueueLLE <E> extends TailedLinkedList <E> implements QueueADT <E> { public boolean offer(E o) { addLast(o); return true; } public E peek() { if (isEmpty()) return null; return getFirst(); public E poll() { E obj = peek(); if (!isEmpty()) removeFirst(); return obj; QueueLLE.java [CS1020 Lecture 9: Stacks and Queues]

[CS1020 Lecture 9: Stacks and Queues] 8 Uses of Queues (1/2) import java.util.*; public class TestStack { public static void main (String[] args) { // you can use any one of the following implementations //QueueArr <String> queue= new QueueArr <String> (); // Array QueueLL <String> queue= new QueueLL <String> (); // LinkedList composition //QueueLLE <String> queue= new QueueLLE <String> (); // LinkedList inheritance System.out.println("queue is empty? " + queue.isEmpty()); queue.offer("1"); System.out.println("operation: queue.offer(\"1\")"); System.out.println("front now is: " + queue.peek()); queue.offer("2"); System.out.println("operation: queue.offer(\"2\")"); queue.offer("3"); System.out.println("operation: queue.offer(\"3\")"); TestQueue.java  [CS1020 Lecture 9: Stacks and Queues]

[CS1020 Lecture 9: Stacks and Queues] 8 Uses of Queues (2/2) queue.poll(); System.out.println("operation: queue.poll()"); System.out.println("front now is: " + queue.peek()); System.out.print("checking whether queue.peek().equals(\"1\"): "); System.out.println(queue.peek().equals("1")); } TestQueue.java  [CS1020 Lecture 9: Stacks and Queues]

java.util.interface Queue <E> [CS1020 Lecture 9: Stacks and Queues]

java.util.interface Queue <E> [CS1020 Lecture 9: Stacks and Queues]

Example Output null mango [mango, banana, orange] [banana, orange]

Example Output true iterator: mango banana orange while: mango banana orange  null []

Application using both Stack and Queue Palindromes Application using both Stack and Queue

10 Application: Palindromes (1/3) A string which reads the same either left to right, or right to left is known as a palindrome Palindromes: “radar”, “deed”, “aibohphobia” Non-palindromes: “data”, “little” input “c1 c2 c3 c4 c5” Algorithm Given a string, use: a Stack to reverse its order a Queue to preserve its order Check if the sequences are the same < c5, c4, c3, c2, c1 > top stack Queue < c1, c2, c3, c4, c5 > front tail [CS1020 Lecture 9: Stacks and Queues]

10 Application: Palindromes (2/3) import java.util.*; public class Palindromes { public static void main (String[] args){ // you can use any of the following stack/queue implementations // and Java classes Stack and LinkedList Stack <String> stack = new Stack <String> (); // Stack is a Java class Queue <String> queue = new LinkedList <String> (); Scanner scanner = new Scanner(System.in); System.out.print("Enter text: "); String inputStr = scanner.next(); for (int i=0; i < inputStr.length(); i++) { String ch = inputStr.substring(i, i+1); stack.push(ch); queue.offer(ch); } Palindromes.java LinkedList is a Java class that implements interface Queue and other interfaces, such as Serializable, Cloneable, Iterable<E>, Collection<E>, Deque<E>, List<E>. [CS1020 Lecture 9: Stacks and Queues]

10 Application: Palindromes (3/3) boolean ans = true; try { while (!stack.isEmpty() && ans) { if (!(stack.pop().equals(queue.poll()))) ans = false; } } catch (NoSuchElementException e) { throw new NoSuchElementException(); System.out.print(inputStr + " is "); if (ans) System.out.println("a palindrome"); else System.out.println("NOT a palindrome"); Palindromes.java [CS1020 Lecture 9: Stacks and Queues]

[CS1020 Lecture 9: Stacks and Queues] 11 Summary We learn to create our own data structures from array and linked list LIFO vs FIFO – a simple difference that leads to very different applications Drawings can often help in understanding the cases still Please do not forget that the Java Library class is much more comprehensive than our own – for sit-in lab or exam, please use the one as told. [CS1020 Lecture 9: Stacks and Queues]

[CS1020 Lecture 9: Stacks and Queues] References Book Stacks: Chapter 7 (recursion excluded) Queues: Chapter 8 CS1020 website  Resources  Lectures http://www.comp.nus.edu.sg/ ~cs1020/2_resources/lectures.html [CS1020 Lecture 9: Stacks and Queues]