220 likes | 353 Views
CM0551 Lecture 6 Stacks and Queues. Stack concepts, applications, example & contract Queue concepts, applications, example & contract. Stack concepts (1).
E N D
CM0551 Lecture 6 Stacks and Queues Stack concepts, applications, example & contract Queue concepts, applications, example & contract
Stack concepts (1) • A stack is a last-in-first-out sequence of elements. Elements can added (push) and removed (pop) only at one end (the top of the stack). • The depth of stack is the number of elements it contains. • An empty stack has depth zero.
2001 Misérables Misérables Initially: After remov-ing a book: After adding “Misérables”: After adding “2001”: Rob Roy War & Peace War & Peace War & Peace War & Peace Moby Dick Moby Dick Moby Dick Moby Dick Stack concepts (2) • Illustration (stack of books):
Stack applications • Interpreter (e.g., the Java Virtual Machine) • maintains a stack containing intermediate results during evaluation of complicated expressions • also containing arguments and return addresses for method calls and returns. • Parser (e.g., a component of the Java compiler) • maintains a stack containing symbols encountered during parsing.
Example: text-file reversal • A text file is a sequence of (zero or more) lines. • To reverse the order of these lines, we must store them in a first-in-last-out sequence. • Text-file reversal algorithm: To output the lines of file in reverse order: 1. Make line-stack empty.2. For each line read from file, repeat: 2.1. Add line to the top of line-stack.3. While line-stack is not empty, repeat: 3.1. Remove a line from the top of line-stack into line. 3.2. Output line.4. Terminate.
Example: bracketing (1) • A phrase is well-bracketed if: • for every left bracket, there is a later matching right bracket • for every right bracket, there is an earlier matching left bracket • the subphrase between a pair of matching brackets is itself well-bracketed. • Examples and counter-examples (maths expressions): s (s – a) (s – b) (s – c) (– b + [b2 – 4ac]) / 2a s (s – a) (s – b (s – c) s (s – a) s – b) (s – c) (– b + [b2 – 4ac)] / 2a well-bracketed well-bracketed ill-bracketed ill-bracketed ill-bracketed
Example: bracketing (2) • Bracket matching algorithm: checks for matches of (), [] or {}. To test whether phrase is well-bracketed: 1. Make bracket-stack empty.2. For each symbol sym in phrase (scanning left to right), repeat: 2.1. If sym is a left bracket: 2.1.1. Add sym to the top of bracket-stack. 2.2. If sym is a right bracket: 2.2.1. If bracket-stack is empty, terminate with false. 2.2.2. Remove a bracket from the top of bracket-stack into left. 2.2.3. If left and sym are not matched brackets, terminate with false. 3. Terminate with true if bracket-stack is empty, or false otherwise.
Stack ADT: requirements • Requirements: • It must be possible to make a stack empty. • It must be possible to add (‘push’) an element to the top of a stack. • It must be possible to remove (‘pop’) the topmost element from a stack. • It must be possible to test whether a stack is empty. • It should be possible to access the topmost element in a stack without removing it.
Stack ADT: contract (1) • Possible contract, expressed as a Java interface*: publicinterface Stack { // Each Stack object is a stack whose elements are objects. /////////////// Accessors /////////////// publicbooleanempty(); // Return true if and only if this stack is empty. public Object peek(); // Return the element at the top of this stack. * an interface is a data type that requires implementing, it’s a class that contains only abstract methods and/or constants – it provides a specification – from programming 2
Stack ADT: contract (2) • Possible contract (continued): ///////////// Transformers ///////////// publicvoid clear (); // Make this stack empty. publicvoidpush(Object elem); // Add elem as the top element of this stack. public Object pop(); // Remove and return the element at the top of this stack. }
Stacks in the Java class library • Java java.util.Stack class does this, but has no clear() function • However, the java.util.LinkedListclass also provides all the Stack operations • clear() is LinkedListclear(), empty() is isEmpty(), peek() is getLast(), push() is addLast(), pop() is removeLast(). importjava.util.LinkedList; LinkedListbookStack = newLinkedList();bookStack.addLast("Moby Dick");bookStack.addLast("War & Peace");bookStack.addLast("Rob Roy");System.out.println(bookStack.removeLast());
Queue concepts (1) • A queue is a first-in-first-out sequence of elements. Elements can added only at one end (the rear of the queue) and removed only at the other end (the front of the queue). • The length of a queue is the number of elements it contains. • An empty queue has length zero.
BUS STOP Queue concepts (2) • Illustration (queue of persons):
Queue applications • Print server • maintains a queue of print jobs. • Disk driver • maintains a queue of disk input/output requests. • Scheduler (e.g., in an operating system) • maintains a queue of processes awaiting a slice of machine time. • Traffic simulation • Maintains many queues of vehicles
Example: demerging (1) • Consider a file of person records, each of which contains a person’s name, gender, date-of-birth, etc. The records are sorted by date-of-birth. We are required to rearrange the records such that females precede males but they remain sorted by date-of-birth within each gender group. • Bad idea: use a sorting algorithm. Time complexity is O(n log n) at best. • Good idea: use a demerging algorithm. Time complexity is O(n).
Example: demerging (2) • Demerging algorithm: To rearrange a file of person records such that females precede males but their order is otherwise unchanged: 1. Make queues females and males empty.2. Until the input file is empty, repeat: 2.1. Let p be the next person read in from the file. 2.2. If p is female, add p to the rear of females. 2.3. If p is male, add p to the rear of males.3. Until females is empty, repeat: 3.1. Write out the person removed from the front of females.4. Until males is empty, repeat: 4.1. Write out the person removed from the front of males.5. Terminate.
Queue ADT: requirements • Requirements: • It must be possible to make a queue empty. • It must be possible to test whether a queue is empty. • It must be possible to obtain the length of a queue. • It must be possible to add an element at the rear of a queue. • It must be possible to remove the front element from a queue. • It must be possible to access the front element in a queue without removing it.
Queue ADT: contract (1) • Possible contract, expressed as a Java interface: publicinterface Queue { // Each Queue object is a queue whose elements are objects. /////////////// Accessors /////////////// publicboolean isEmpty (); // Return true if and only if this queue is empty. publicint size (); // Return this queue’s length. public Object getFirst (); // Return the element at the front of this queue.
Queue ADT: contract (2) • Possible contract (continued): /////////////// Transformers /////////////// publicvoid clear (); // Make this queue empty. publicvoid addLast (Object elem); // Add elem as the rear element of this queue. public Object removeFirst (); // Remove and return the front element of this queue. }
Queue interface public interface Queue<E> extends Collection<E> { E element(); boolean offer(E o); E peek(); E poll(); E remove(); }
Queue Interface continued • Each Queue method exists in two forms: • one throws an exception if the operation fails • the other returns a special value (either null or false, depending on the operation). Queue Interface Structure
Queues in the Java class library • The java.util.LinkedList class provides all the Queue operations, for example importjava.util.LinkedList; LinkedList<String> queue = newLinkedList<String>();queue.addLast("Homer"); queue.addLast("Marge"); queue.addLast("Bart"); queue.addLast("Lisa"); queue.addLast("Maggie"); System.out.println(queue.removeFirst());