CmpSci 187: Programming with Data Structures Spring 2015



Similar documents
Programming with Data Structures

DATA STRUCTURE - QUEUE

Common Data Structures

Chapter 3: Restricted Structures Page 1

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

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

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

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

DATA STRUCTURE - STACK

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

Analysis of a Search Algorithm

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

J a v a Quiz (Unit 3, Test 0 Practice)

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

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

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

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

Linked Lists Linked Lists, Queues, and Stacks

STACKS,QUEUES, AND LINKED LISTS

Module 2 Stacks and Queues: Abstract Data Types

Universidad Carlos III de Madrid

7.1 Our Current Model

Project 2: Bejeweled

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

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

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

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

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Stacks. Linear data structures

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

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

Algorithms and Data Structures Written Exam Proposed SOLUTION

CompSci-61B, Data Structures Final Exam

14 Stacks, Queues, And Linked Lists

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

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

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

Sequential Data Structures

Java Interview Questions and Answers

Lecture Notes on Stacks & Queues

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

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

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:

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

C++ INTERVIEW QUESTIONS

Data Structures and Algorithms Stacks and Queues

Hash Tables. Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Data Dictionary Revisited

Linked Lists: Implementation Sequences in the C++ STL

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

10CS35: Data Structures Using C

Iteration CHAPTER 6. Topic Summary

DATA STRUCTURES USING C

Introduction to Data Structures

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

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

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

Abstract Data Types. Chapter 2

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

Sequences in the C++ STL

PES Institute of Technology-BSC QUESTION BANK

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

Node-Based Structures Linked Lists: Implementation

Algorithms and Data Structures

ADTs,, Arrays, Linked Lists

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

COMPUTER SCIENCE. Paper 1 (THEORY)

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

1. Define: (a) Variable, (b) Constant, (c) Type, (d) Enumerated Type, (e) Identifier.

TEXAS HOLD EM POKER FOR SIGHT

Practical Session 4 Java Collections

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

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

Moving from CS 61A Scheme to CS 61B Java

Programming Exercises

CS 111 Classes I 1. Software Organization View to this point:

The ADT Binary Search Tree

Ready, Set, Go! Math Games for Serious Minds

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

25 Integers: Addition and Subtraction

Stack Allocation. Run-Time Data Structures. Static Structures

13 Classes & Objects with Constructors/Destructors

Introduction to Data Structures and Algorithms

Text Processing In Java: Characters and Strings

public static void main(string[] args) { System.out.println("hello, world"); } }

Lecture 2: Data Structures Steven Skiena. skiena

AN ANALYSIS OF A WAR-LIKE CARD GAME. Introduction

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

Stacks. Data Structures and Data Types. Collections

Review of Hashing: Integer Keys

CMSC 202H. ArrayList, Multidimensional Arrays

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

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

Introduction to Java

LINKED DATA STRUCTURES

1 Abstract Data Types Information Hiding

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

Data Structures and Data Manipulation

Introduction to Stacks

Transcription:

CmpSci 187: Programming with Data Structures Spring 2015 Lecture #12 John Ridgway March 10, 2015 1 Implementations of Queues 1.1 Linked Queues A Linked Queue Implementing a queue with a linked list is very natural. We keep head and tail pointers, enqueue at the tail and dequeue at the head. LinkedQueue tail: head: Node next: data: Node next: data: Node next: data: "A" "B" "C" A Linked Queue (continued) Could we have done this the other way round, with the front of the queue at the tail of the list? Enqueuing would have been easy, but dequeuing would have meant removing an element from the tail of the list, which means setting the tail pointer to the penultimate node. Code for the Linked Queue We make our generic queue from Node<T> objects. public class LinkedUnbndQueue <T> implements UnboundedQueueInterface <T> { private Node <T> head ; 1

private Node <T > tail ; public LinkedUnbndQueue () { head = null ; tail = null ; Enqueuing in the Linked Queue To enqueue an element, we must make a new node and splice it into the list at the tail. public void enqueue ( T element ) { Node <T > newnode = new Node <T >( element ); if ( tail == null ) { head = newnode ; else { tail. setnext ( newnode ); tail = newnode ; The dequeue Operation To dequeue, we remember the contents of the front node, cut it out of the list, and return the contents. public T dequeue () { if ( isempty ()) { throw new QueueUnderflowException (); else { T element = head. getdata (); head = head. getnext (); if ( head == null ) { tail = null ; return element ; Clicker Question #1 In the code below, the last line has replaced tail = newnode;. What s wrong with this? public void enqueue ( T element ) { Node <T > newnode = new Node <T >( element ); if ( tail == null ) { head = newnode ; else { tail. setnext ( newnode ); tail = tail. getnext (); A. the old tail node gets a pointer to itself B. there s an NPE if the queue is empty 2

C. the old tail node gets garbage-collected D. the tail node shouldn t change for enqueue 1.2 Applications: Palindromes Applications: Palindromes A palindrome is a string that is the same when written backward, like Hannah, Able was I ere I saw Elba, or Madam, I m Adam. Here s a simple way to test whether a string is a palindrome: Create a stack and a queue (of Characters) and read the entire string, putting a copy of each letter (not spaces or punctuation) into both the stack and queue; Pop and dequeue one character at a time, checking that they match. If we empty both the stack and queue without finding a mismatch, the original string was a palindrome. Palindrome Code: Part I public class Palindrome { public static boolean test ( String candidate ) { USI < Character > stack = new LinkedStack < Character >(); UQI < Character > queue = new LinkedQueue < Character >(); for ( int i = 0; i < candidate. length ; i ++) { char ch = candidate. charat ( i); if ( Character. isletter (ch )) { char lowercase = Character. tolowercase ( ch ); stack. push ( lowercase ); queue. enqueue ( lowercase ); Palindrome Code: Part II boolean stillok = true ; while ( stillok &&! stack. isempty ()) { char fromstack = stack. pop (); // unboxing char fromqueue = queue. dequeue (); // unboxing if ( fromstack!= fromqueue ) { stillok = false ; return stillok ; 3

Clicker Question #2 Here s a way to test whether a string is a palindrome recursively. If the first letter and last letter do not match, return false. Otherwise recurse on the string without those two letters. What is the base case of this recursion? A. it doesn t matter as the recursion is invalid B. return true on a string with no letters C. return true if there is zero or one letter D. return false if there is one letter, true if 0 1.3 Array-based Queues The Array Queues Way Since a queue is a list of elements with a fixed order, a natural thought is to place the elements in an array: enqueue A r=rear enqueue B enqueue C dequeue A r 0 1 2 3 4 B C Avoiding Shifting the Array We had to shift them, which gets expensive, so why not keep track of the front too? f=front r=rear f r 0 1 2 3 4 enqueue A enqueue B enqueue C dequeue A enqueue D enqueue E B C D E Circular Queues But now we run out of space. So wrap-around and put enqueued elements at beginning of the array: 4

f=front r=rear r f 0 1 2 3 4 F G C D E enqueue A enqueue B enqueue C dequeue A enqueue D enqueue E enqueue F dequeue B enqueue G Implementing a Circular Queue Instead of incrementing the index into the array with an instruction like index++, we instead say index = (index + 1) \% capacity. Remember that the Java \% operator gives us the remainder when its first argument is divided by the second. So in this way location capacity - 1 is followed by location 0. Clicker Question #3 The elements in the queue start at location front and continue to location rear. Which of these expressions gives the number of elements in the queue, assuming the queue is not empty? A. (rear - front) % capacity B. (rear - front + 1) % capacity C. (front - rear + 1) % capacity D. (rear+capacity+1 - front) % capacity Coding the Circular Queue Note that a full queue and an empty queue both have rear just before front. But we keep track of numelements, which tells these two cases apart. Circular Queue Attributes and Constructors public class ArrayBndQueue <T > implements BQI <T > { private final int DEFCAP = 100; private T[] queue ; private int numelements = 0; private int front = 0; private int rear = -1; public ArrayBndQueue ( int maxsize ) { queue = (T []) new Object [ maxsize ]; 5

public ArrayBndQueue () { this ( DEFCAP ); Circular Queue Transformers public void enqueue ( T element ) { if ( isfull ()) { throw new QOE (); rear = ( rear +1) % queue. length ; queue [ rear ] = element ; numelements += 1; public T dequeue () { if ( isempty ()) { throw new QUE (); T toreturn = queue [ front ]; queue [ front ] = null ; front = ( front numelements -= + 1) 1; % queue. length ; return toreturn ; Circular Queue Observers public boolean isempty () { return ( numelements == 0); public boolean isfull () { return numelements == queue. length ; Application: The Game of War War is a two-player card game that calls for no decision-making by either player. You shuffle the deck and play deterministically until the game ends. Each player has a hand, originally half the deck. A basic play is for each player to turn up the first card in their hand. The player with the higher rank card wins both cards and puts them at the end of their hand. The Game of War If the two cards have the same rank, each player deals out three cards face-down from their hand and turns up the next card in their hand. The player with the higher-ranked of these wins all ten cards now on the table. If those two cards have equal rank, each player plays four more cards for a second war, and so on until there is a resolution or one player runs out of cards. 6

Simulating the Game of War We first need to create and shuffle a virtual deck of cards DJW s code is worth keeping in mind for future reference though we won t reproduce it here Our deck is an array of ints in the range from 0 through 12, since we don t care about suits We form an array with four of each rank, then shuffle using a Random object. For each position in turn, we choose a random position after it and swap those two cards Simulating the Game of War DJW s WarGame class sets up two queues of Integers for the players hands, and a third queue prize for the cards that will be won in the current battle, if any. A variable, set by the user, limits the number of battles that may happen before the game is abandoned. The play method in WarGame deals the cards into the two player s hands and then runs battles until the game ends. Simulating the Game of War The battle method puts the players next cards into the prize queue, then checks the ranks of those two cards. If they are different, it puts the cards in the prize queue into the winner s hand. If they are the same, it puts three cards from each player into the prize queue, then recursively calls itself. If a player runs out of cards, a QueueUnderflowException is thrown and caught by the play method, which declares the game over and keeps going. Comparing the Implementations We ve been careful in both implementations to make the enqueue and dequeue operations each O(1) time (not always the same time, of course, but at most different by a constant factor ). The constructor for a linked queue is also O(1), but the constructor for an array with initial size N takes O(N) time. 7

Comparing the Implementations An exception is the unbounded array implementation, which might take O(N) time with N items in the queue if it has to resize the array. As we ve noted, if we double the array size each time we change it, the total time to resize the array up to size N turns out to be O(N), or an amortized O(1) per enqueue. Individual enqueues might be slower, but we have the guarantee about the total time Comparing the Implementations The linked structure uses an extra pointer in each node, doubling the space needed for the pointer to the element object. The array implementation uses the space for the unused entries in the array. Thus if the array is always at least half full, the array implementation uses less space, but both use only O(N) space for a queue whose maximum size over time is N elements. 8