1 CSC 321: Data Structures Fall 2013 Lists, stacks & queues  Collection classes: ─List (ArrayList, LinkedList), Set (TreeSet, HashSet), Map (TreeMap,

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

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)
Stack & Queues COP 3502.
Data Structures Lecture 13: QUEUES Azhar Maqsood NUST Institute of Information Technology (NIIT)
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.
Data Structure (Part I) Stacks and Queues. Introduction to Stack An stack is a ordered list in which insertion and deletions are made at one end. –The.
Queues 4/14/2017 5:24 PM 5.2 Queues Queues Dr Zeinab Eid.
Queues Ellen Walker CPSC 201 Data Structures Hiram College.
Today’s Agenda  Stacks  Queues  Priority Queues CS2336: Computer Science II.
CHAPTER 4 Queues. Queue  The queue, like the stack, is a widely used data structure  A queue differs from a stack in one important way  A stack is.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Lecture 8 CS203. Implementation of Data Structures 2 In the last couple of weeks, we have covered various data structures that are implemented in the.
1 CSC 222: Computer Programming II Spring 2004 Queues and simulation  queue ADT  enqueue (push), dequeue (pop), front, empty, size  library  application:
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
1 Chapter 24 Lists Stacks and Queues. 2 Objectives F To design list with interface and abstract class (§24.2). F To design and implement a dynamic list.
1 Queues Queue Concept Queue Design Considerations Queues in Java Collections APIs Queue Applications Reading L&C , 9.3.
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, Queues & Deques CSC212.
TCSS 342, Winter 2005 Lecture Notes
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 26 Implementing Lists, Stacks,
CSC 212 – Data Structures Lecture 21: IndexList a/k/a Vector, ArrayList.
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
Building Java Programs
1 CSC 222: Computer Programming II Spring 2005 Queues and simulation  queue ADT enqueue (offer), dequeue (remove), peek, empty, size  java.util.Queue.
ADT Stacks and Queues. Stack: Logical Level “An ordered group of homogeneous items or elements in which items are added and removed from only one end.”
Topic 3 The Stack ADT.
1 CSC 222: Computer Programming II Spring 2005 Stacks and recursion  stack ADT  push, pop, peek, empty, size  ArrayList-based implementation, java.util.Stack.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Chapter 7 Stacks I CS Data Structures I COSC 2006 April 22, 2017
Adapted from instructor resources Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Information and Computer Sciences University of Hawaii, Manoa
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
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.
LinkedList Many slides from Horstmann modified by Dr V.
1 Chapter 17 Object-Oriented Data Structures. 2 Objectives F To describe what a data structure is (§17.1). F To explain the limitations of arrays (§17.1).
HIT2037- HIT6037 Software Development in Java 22 – Data Structures and Introduction.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 8 Collection.
1 Chapter 20 Lists, Stacks, Queues Lecture 7 Dr. Musab Zghoul برمجة هيكلية.
COP INTERMEDIATE JAVA Data Structures. A data structure is a way of organizing a collection of data so that it can be manipulated effectively. A.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
Stacks and Queues. 2 3 Runtime Efficiency efficiency: measure of computing resources used by code. can be relative to speed (time), memory (space), etc.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Generics and Collections Course Lecture Slides 19 th July 2010 “Never.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
1 CSC 321: Data Structures Fall 2012 Lists, stacks & queues  Collection classes: ─List (ArrayList, LinkedList), Set (TreeSet, HashSet), Map (TreeMap,
(c) University of Washington16-1 CSC 143 Java Lists via Links Reading: Ch. 23.
Data Structures & Algorithms
1 CSC 427: Data Structures and Algorithm Analysis Fall 2010 Java Collections & List implementations  Collection classes: ─List (ArrayList, LinkedList),
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
1 CSC 321: Data Structures Fall 2012 Linked structures  nodes & recursive fields  singly-linked list  doubly-linked list  LinkedList implementation.
List Interface and Linked List Mrs. Furman March 25, 2010.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
1 CSC 222: Computer Programming II Spring 2004 Stacks and recursion  stack ADT  push, pop, top, empty, size  vector-based implementation, library 
Copyright © Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Click to edit Master text styles Stacks Data Structure.
CSCI 62 Data Structures Dr. Joshua Stough September 23, 2008.
Marcus Biel, Software Craftsman
CSC 427: Data Structures and Algorithm Analysis
CSC 321: Data Structures Fall 2016 Linked structures
Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues
CSC 321: Data Structures Fall 2013 Linked structures
CSC 321: Data Structures Fall 2018 Linked structures
CSC 321: Data Structures Fall 2018 Lists, stacks & queues
Collections Framework
CSC 427: Data Structures and Algorithm Analysis
Presentation transcript:

1 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 performance  Stacks  Queues

2 Java Collection classes a collection is an object (i.e., data structure) that holds other objects the Java Collection Framework is a group of generic collections  defined using interfaces abstract classes, and inheritance more on Sets & Maps later

3 ArrayList performance recall: ArrayList implements the List interface  which is itself an extension of the Collection interface  underlying list structure is an array get(index), add(item), set(index, item)  O(1) add(index, item), indexOf(item), contains(item), remove(index), remove(item)  O(N)

4 ArrayList implementation the ArrayList class has as fields  the underlying array  number of items stored the default initial capacity is defined by a constant  capacity != size public class MyArrayList implements Iterable { private static final int INIT_SIZE = 10; private E[] items; private int numStored; public MyArrayList() { this.clear(); } public void clear() { this.numStored = 0; this.ensureCapacity(INIT_SIZE); } public void ensureCapacity(int newCapacity) { if (newCapacity > this.size()) { E[] old = this.items; this.items = (E[]) new Object[newCapacity]; for (int i = 0; i < this.size(); i++) { this.items[i] = old[i]; }. interestingly: you can't create a generic array this.items = new E[capacity]; // ILLEGAL can work around this by creating an array of Objects, then casting to the generic array type

5 ArrayList: add the add method  throws an exception if the index is out of bounds  calls ensureCapacity to resize the array if full  shifts elements to the right of the desired index  finally, inserts the new value and increments the count the add-at-end method calls this one public void add(int index, E newItem) { this.rangeCheck(index, "ArrayList add()", this.size()); if (this.items.length == this.size()) { this.ensureCapacity(2*this.size() + 1); } for (int i = this.size(); i > index; i--) { this.items[i] = this.items[i-1]; } this.items[index] = newItem; this.numStored++; } private void rangeCheck(int index, String msg, int upper) { if (index upper) throw new IndexOutOfBoundsException("\n" + msg + ": index " + index + " out of bounds. " + "Should be in the range 0 to " + upper); } public boolean add(E newItem) { this.add(this.size(), newItem); return true; }

6 ArrayList: size, get, set, indexOf, contains size method  returns the item count get method  checks the index bounds, then simply accesses the array set method  checks the index bounds, then assigns the value indexOf method  performs a sequential search contains method  uses indexOf public int size() { return this.numStored; } public E get(int index) { this.rangeCheck(index, "ArrayList get()", this.size()-1); return items[index]; } public E set(int index, E newItem) { this.rangeCheck(index, "ArrayList set()", this.size()-1); E oldItem = this.items[index]; this.items[index] = newItem; return oldItem; } public int indexOf(E oldItem) { for (int i = 0; i < this.size(); i++) { if (oldItem.equals(this.items[i])) { return i; } return -1; } public boolean contains(E oldItem) { return (this.indexOf(oldItem) >= 0); }

7 ArrayList: remove the remove method  checks the index bounds  then shifts items to the left and decrements the count  note: could shrink size if becomes ½ empty the other remove  calls indexOf to find the item, then calls remove(index) public void remove(int index) { this.rangeCheck(index, "ArrayList remove()", this.size()-1); for (int i = index; i < this.size()-1; i++) { this.items[i] = this.items[i+1]; } this.numStored--; } public boolean remove(E oldItem) { int index = this.indexOf(oldItem); if (index >= 0) { this.remove(index); return true; } return false; } could we do this more efficiently? do we care?

8 ArrayLists vs. LinkedLists LinkedList is an alternative List structure  stores elements in a sequence but allows for more efficient interior insertion/deletion  elements contain links that reference previous and successor elements in the list  can access/add/remove from either end in O(1)  if given a reference to an interior element, can reroute the links to add/remove an element in O(1) [more later when we consider iterators] getFirst(), getLast(), add(item), addFirst(), addLast() removeFirst(), removeLast()  O(1) get(index), set(index, item), add(index, item), indexOf(item), contains(item), remove(index), remove(item)  O(N) front null 5 back 46

9 Lists & stacks stack  a stack is a special kind of (simplified) list  can only add/delete/look at one end (commonly referred to as the top) DATA:sequence of items OPERATIONS:push on top, peek at top, pop off top, check if empty, get size these are the ONLY operations allowed on a stack — stacks are useful because they are simple, easy to understand — each operation is O(1)  PEZ dispenser  pile of cards  cars in a driveway  method activation records (later) a stack is also known as  push-down list  last-in-first-out (LIFO) list

10 Stack examples top peek()  3 push(4) pop()  top

11 Stack exercise start with empty stack PUSH 1 PUSH 2 PUSH 3 PEEK PUSH 4 POP PEEK PUSH 5

12 Stack class since a stack is a common data structure, a predefined Java class exists import java.util.Stack;  Stack is generic to allow any type of object to be stored Stack wordStack = new Stack (); Stack numStack = new Stack ();  standard Stack methods public T push(T item); // adds item to top of stack public T pop();// removes item at top of stack public T peek();// returns item at top of stack public boolean empty();// returns true if empty public int size();// returns size of stack

13 Stack application consider mathematical expressions such as the following  a compiler must verify such expressions are of the correct form (A * (B + C))([A * (B + C)] + [D * E]) attempt 1: count number of left and right delimeters; if equal, then OK what about:(A * B) + )C( stack-based solution:  start with an empty stack of characters  traverse the expression from left to right if next character is a left delimiter, push onto the stack if next character is a right delimiter, must match the top of the stack attempt 2: start a counter at 0, +1 for each left delimiter and -1 for each right if it never becomes negative and ends at 0, then OK what about:([A + B) + C]

14 Delimiter matching import java.util.Stack; public class DelimiterChecker { private static final String DELIMITERS = "()[]{}<>"; public static boolean check(String expr) { Stack delimStack = new Stack (); for (int i = 0; i < expr.length(); i++) { char ch = expr.charAt(i); if (DelimiterChecker.isLeftDelimiter(ch)) { delimStack.push(ch); } else if (DelimiterChecker.isRightDelimiter(ch)) { if (!delimStack.empty() && DelimiterChecker.match(delimStack.peek(), ch)) { delimStack.pop(); } else { return false; } return delimStack.empty(); } how would you implement the helpers? isLeftDelimiter isRightDelimiter match

15 Run-time stack when a method is called in Java (or any language):  suspend the current execution sequence  allocate space for parameters, locals, return value, …  transfer control to the new method when the method terminates:  deallocate parameters, locals, …  transfer control back to the calling point (& possibly return a value) note: method invocations are LIFO entities  main is called first, terminates last  if main calls foo and foo calls bar, then bar terminates before foo which terminates before main  a stack is a natural data structure for storing information about method calls and the state of the execution

16 Run-time stack (cont.) an activation record stores info (parameters, locals, …) for each invocation of a method  when the method is called, an activation record is pushed onto the stack  when the method terminates, its activation record is popped  note that the currently executing method is always at the top of the stack public class Demo { public static void main(String[] args) { int x = 12; Demo.foo(x); System.out.println("main " + x); } public static void foo(int a) { a++; System.out.println("foo " + a); } main: x = automatically start with main main: x = when foo called, push foo: a = main: x = when foo done, pop when main done, pop & end

17 Lists & queues queues  a queue is another kind of simplified list  add at one end (the back), delete/inspect at other end (the front) DATA:sequence of items OPERATIONS:add(enqueue/offer at back), remove(dequeue off front), peek at front, check if empty, get size these are the ONLY operations allowed on a queue — queues are useful because they are simple, easy to understand — each operation is O(1)  line at bank, bus stop, grocery store, …  printer jobs  CPU processes  voice mail a queue is also known as  first-in-first-out (FIFO) list

18 Queue examples 321 frontback 321 front 4 back 32 front back 321 frontback peek()  1 add(4) remove()  1

19 Queue exercise start with empty queue ADD 1 ADD 2 ADD 3 PEEK ADD 4 REMOVE PEEK ADD 5

20 Queue interface Queue numQ = new LinkedList (); for (int i = 1; i <= 10; i++) { numQ.add(i); } while ( !numQ.empty() ) { System.out.println(numQ.peek()); numQ.remove(); } a queue is a common data structure, with many variations  Java provides a Queue interface  also provides several classes that implement the interface (with different underlying implementations/tradeoffs) java.util.Queue interface public boolean add(T newItem); public T remove(); public T peek(); public boolean empty(); public int size(); java.util.LinkedList implements the Queue interface Queue q1 = new LinkedList (); Queue q2 = new LinkedList (); for (int i = 1; i <= 10; i++) { q1.add(i); } while ( !q1.empty() ) { q2.add(q1.remove()); } while ( !q2.empty() ) { System.out.println(q2.remove()); }

21 Queues and simulation queues are especially useful for simulating events e.g., consider simulating a 1-teller bank  customers enter a queue and are served FCFS (or FIFO)  can treat the arrival of a customer and their transaction length as random events What is the time duration (in minutes) to be simulated? 10 What percentage of the time (0-100) does a customer arrive? 30 2: Adding customer 1 (job length = 4) 2: Serving customer 1 (finish at 6) 4: Adding customer 2 (job length = 3) 6: Finished customer 1 6: Serving customer 2 (finish at 9) 9: Finished customer 2 if multiple tellers are available,  could have a separate queue for each teller (FAIRNESS ISSUES?)  or, could still have one queue, whenever a teller becomes free he/she serves the customer at the front

HW 2 for HW2, you will model a vibrating piano wire  the length of the wire determines the pitch/frequency can model the vibration using a queue of sample values, taken by measuring the frequency displacement at set intervals  at rest, the wire can contain energy at any frequency can model this by storing random values in range -0.5 to 0.5  when struck, the vibration causes a displacement that spreads like a wave can model this using a very simple queue update algorithm known as the Karplus-Strong update 22

Karplus-Strong algorithm at each time step, update the queue of frequency displacements by:  remove the sample at the front of the queue  add a new sample at the rear of the queue that is the average of the old front & new front, multiplied by a decay factor (0.996) 23