Presentation is loading. Please wait.

Presentation is loading. Please wait.

Stacks, Queues, Linked Lists, Deques

Similar presentations


Presentation on theme: "Stacks, Queues, Linked Lists, Deques"— Presentation transcript:

1 Stacks, Queues, Linked Lists, Deques
COMP-2001 L Stacks, Queues, Linked Lists, Deques Abstract Data Types (ADTs) Interfaces and implementations Stacks, queues, linked lists, dequeues Java implementations This week: - complete P1-P3 - start P4 - read Next week: - complete P4 - read Portions copyright Goodrich & Tommassia!

2 More terminology: Abstract Data Types (ADTs)
An Abstract Data Type is an abstract specification of a data structure what operations can be involved on an instance of the ADT Perhaps: invariants that are guaranteed to hold if the ADT is used properly No code! Java’s “interface” construct is for specifying ADTs (except invariants!) For example, if we are going to model a bag of marbles as an ADT, we could specify that: Operations this ADT stores marbles this ADT supports putting in a marble and getting out a marble. Invariants No marbles are ever lost or spontaneously generated

3 Abstract Data Types (ADTs)
There are lots of formalized and standard ADTs. (A bag of marbles is not one of them.) In this course we are going to learn a lot of different standard ADTs. (stacks, queues, trees...)

4 Stacks A stack is a container of objects that are inserted and removed according to the last-in-first-out (LIFO) principle. Objects can be inserted at any time, but only the last (the most-recently inserted) object can be removed. Inserting an item is known as “pushing” onto the stack. “Popping” off the stack means removing an (the M-R-U!) item. A PEZ® dispenser as an analogy:

5 The Stack Abstract Data Type
A stack is an abstract data type (ADT) that supports two main methods: push(o): Inserts object o onto top of stack pop(): Removes the top object of stack and returns it; if the stack is empty, an error occurs The following support methods should also be defined: size(): Returns the number of objects in stack isEmpty(): Return a boolean indicating if stack is empty. top(): Return the top object of the stack, without removing it; if the stack is empty, an error occurs.

6 Stack Example #1 2 3 1 Laundry Basket

7 Example #2: Stacks in the Java Virtual Machine
Each process running in a Java program has its own Java Method Stack. Each time a method is called, it is pushed onto the stack. The choice of a stack for this operation allows Java to do several useful things: Perform recursive method calls Print stack traces to locate an error

8 Java Method Stack newest method context oldest method context

9 Java stuff See lectures 3-4!
Given the stack ADT, we need to code the ADT in order to use it in the programs. You need to understand two program constructs: interfaces and exceptions. An interface is a way to declare what a class is to do. It does not mention how to do it. For an interface, you just write down the method names and the parameters. When specifying parameters, what really matters is their types. Later, when you write a class for that interface, you actually code the content of the methods. Separating interface and implementation is a useful programming technique. Interface example: See lectures 3-4!

10 A Stack Interface in Java
public interface Stack { // accessor methods public int size(); public boolean isEmpty(); public Object top() throws StackEmptyException; // update methods public void push (Object element); public Object pop() throws StackEmptyException; } (yes - Java has a built-in Stack utility class!)

11 Array-Based Stack in Java
We want to implement our Stack interface. Lots of possibilities… one simple technique is to use an array public class ArrayStack implements Stack { ? }

12 An Array-Based Stack implementation
Create a stack using an array by specifying a maximum size N for our stack, e.g., N = 1000. The stack consists of an N-element array S and an integer variable t, the index of the top element in array S. Algorithm size(): return t +1 Algorithm isEmpty(): return (t < 0) Algorithm top(): if isEmpty() then throw a StackEmptyException return S[t] ... NOTE: Array indices start at 0, so we initialize t to -1 Pseudo-code is to the right.

13 Pseudo-Code (contd.) Algorithm push(o): if size() = N then
the Stack interface doesn’t know/care about this situation, becomes stacks “in the abstract” have infinite capacity. However, our simple array implementation does not handle this requirement, so we need to introduce an extra exception even though it isn’t mentioned in Stack Algorithm push(o): if size() = N then throw a StackFullException t  t + 1 S[t]  o Algorithm pop(): if isEmpty() then throw a StackEmptyException e  S[t] S[t]  null t  t-1 return e Enable garbage collection (re-use of S[t]’s memory, if not referenced elsewhere in program execution).

14 An Array-Based Stack (contd.)
Both the push and pop methods runs in O(1) time The array implementation is simple and efficient. There is a predefined upper bound, N, on the size of the stack, which may be too small for a given application, or cause a waste of memory. StackEmptyException is required by the interface. StackFullException is particular to this implementation. Algorithm pop(): if isEmpty() then throw a StackEmptyException e  S[t] S[t]  null t  t-1 return e Algorithm push(o): if size() = N then throw a StackFullException t  t + 1 S[t]  o “f(n)=O(1)” means “f(n) is a constant, independent of n”

15 Array-Based Stack in Java
public class ArrayStack implements Stack { // Implementation of the Stack interface using an array. public static final int CAPACITY = 1000; // default capacity of the stack private int capacity; // maximum capacity of the stack. private Object S[ ]; // S holds the elements of the stack private int top = -1; // the top element of the stack. public ArrayStack( ) { // Initialize the stack this(CAPACITY);// with default capacity } public ArrayStack(int cap) { // Initialize the stack with given capacity capacity = cap; S = new Object[capacity]; }

16 Array-Based Stack in Java (contd.)
public int size( ) { //Return the current stack size return (top + 1); } public boolean isEmpty( ) { // Return true iff the stack is empty return (top < 0); public void push(Object obj) throws StackFullException{ // Push a new element on the stack if (size() == capacity) { throw new StackFullException(“Stack overflow.”); S[++top] = obj;

17 Array-Based Stack in Java (contd.)
public Object top( )// Return the top stack element throws StackEmptyException { if (isEmpty( )) { throw new StackEmptyException(“Stack is empty.”); } return S[top]; public Object pop() // Pop off the stack element throw new StackEmptyException(“Stack is Empty.”); Object elem = S[top]; S[top--] = null; // Dereference S[top] and decrement top return elem;

18 Array-Based Stack in Java (contd.)
class StackFullException extends RunTimeException { // don’t need anything in here! } class StackEmptyException extends RunTimeException { Complete code available from COMP web page

19 Casting With a Generic Stack
Have an ArrayStack that can store only Integer objects or Student objects. In order to do so using a generic stack, the return objects must be cast to the correct data type. A Java code example: Integer year = new Integer(2001); Stack s = new ArrayStack(); // Stacks can only store Objects s.push(year); // Returned values usually must be cast to appropriate class int y = ((Integer) s.pop()).intValue();

20 Lec 9 - Queues enter at end of line exit from front of queue
This week: - complete P4, start P5 - finish reading chap 4 Next week: - complete P5 - read

21 Queues A queue differs from a stack in that its insertion and removal routines follows the first-in-first-out (FIFO) principle. (Remember: Stack=LIFO) Elements may be inserted at any time, but only the element which has been in the queue the longest may be removed. Elements are inserted at the rear (enqueued) and removed from the front (dequeued)

22 Queue example - Web spider
Search engines (Altavista, Google, etc) uses programs called spiders to discover new pages on the web (which can then be indexed for searching, but that’s another story…) Input = some particular seed page Repeatedly: select a previously-discovered page, and traverse one of its hyperlinks. To ensure broad coverage of the entire web, spiders employ a queue data-structure to store & select discovered pages newly discovered pages next page to be explored

23 The Queue Abstract Data Type
The queue has two fundamental methods: enqueue(o): Insert object o at the rear of the queue dequeue(): Remove the object from the front of the queue and return it; an error occurs if the queue is empty These support methods should also be defined: size(): Return the number of objects in the queue isEmpty(): Return a boolean value that indicates whether the queue is empty front(): Return, but do not remove, the front object in the queue; an error occurs if the queue is empty

24 Queue ADT: Java interface code
interface Queue { boolean isEmpty(); int size(); Object front() throws QueueEmptyException; Object dequeue() throws QueueEmptyException; void enqueue(Object); }

25 An Array-Based Queue Create a queue using an array in a circular fashion A maximum size N is specified, e.g. N = 1,000. The queue consists of an N-element array Q and two integer variables: -f, index of the front element (initially, f=0) -r, index of the element after the rear one (initially r=0) “normal configuration” Questions: What does f=r mean? How do we compute the number of elements in the queue from f and r?

26 An Array-Based Queue (contd.)
Algorithm size(): return (N - f + r) mod N Algorithm isEmpty(): return size() < 1; Algorithm front(): if isEmpty() then throw a QEmptyException return Q[f] Algorithm dequeue(): if isEmpty() then throw a QEmptyException temp  Q[f] Q[f]  null f  (f + 1) mod N return temp Algorithm enqueue(o): if size = N - 1 then throw a QFullException Q[r]  o r  (r+1) mod N

27 An Array-Based Queue - Java Code
public class ArrayQueue implements Queue { private final static int CAPACITY = 100; private int capacity; private Object[] Q; private int f; private int r; public ArrayQueue() { this(CAPACITY); } public ArrayQueue(int _capacity) { capacity = _capacity; Q = new Object[capacity]; f = r = 0; public int size() { // your code goes here! (Practical 6) public boolean isEmpty() {

28 Array-Queue Java code - Con’d
public void enqueue(Object o) throws QueueFullException { // your code goes here! (Practical 6) } public Object front() throws QueueEmptyException { public Object dequeue() throws QueueEmptyException {

29 Lec 10 - Linked lists

30 Linked lists Arrays are one way to implement Stacks, queues, etc. Linked Lists are another -- extremely flexible and general idea! Linked list = “Node” objects connected in a “chain” by links (object references) Special “entry point” reference null Stored values (eg, Strings) Boxes are “Node” objects (not ‘built in’ -- you must define/manage them!)

31 Node objects class Node { Node next; // the next Node in the list
Object element; // the data } Wow - a class defined in terms of itself! Don’t be scared….. element next “Rome” Null means “end of list”

32 A useful trick Two special entry points null head tail
If we maintain these two special entry points, it is easy to delete or insert entries at the “head” and insert entries at the “tail” (but still tricky to delete entries at the “tail” -- why??!) insert delete    

33 Removing at the Head 1. 2. removed item

34 Inserting at the Tail new item 1. 2.

35 The point of all this is….. Using linked lists to implement Queue
Leave queue enter queue null The head of the list is the front of the queue, and the tail of the list is the rear of the queue. Why not the opposite? LinkedListQueue is an alternative implementation of Queue to ArrayQueue. Unlimited capacity -- no wasted memory, no more QueueFullException

36 Linked List implementation of Queue - Java
public class LinkedListQueue implements Queue { private Node front; private Node rear; private int size; private class Node { // Node is an “inner” class since no one else will ever need it Object element; Node next; Node(Object _element, Node _next) { element = _element; next = _next; } public LinkedListQueue() { front = rear = null; size = 0; Guarantees we’ll provide same methods as ArrayQueue

37 LinkedListQueue - continued
public int size() { return size; } public boolean isEmpty() { return size==0; public void enqueue(Object o) { // your code goes here -- Practical 6! public Object front() throws QueueEmptyException { public Object dequeue() throws QueueEmptyException {

38 Lec 11 - Deques 2 detours: more O(.), pointers/references, then…
This week: - complete P5 - start P6 - read Chapter 5 Next week: - no lecture Monday - bank holiday!

39 Digression 1. More O(·) “3n n is O(n2)” means “as n gets larger, eventually n2 becomes larger than 3n2+100n (when linearly scaled up) n0 = c = 4  n>n0 cn2>3n2+100 “eventually” n0

40 More O(·) “f(n) is O(g(n))” means “as n gets larger, eventually f(n) becomes larger than g(n) (when linearly scaled up by some amount) n0 = ? c = ?  n>n0: c·g(n)>f(n) numbers you need to find in order to prove that f(n) is O(g(n)) c·g(n) f(n) g(n) n n0

41 O(·) cheat-sheet The formal (c,no) definition is needed sometimes, but usually the following simple rules of thumb suffices: Discard all constants Discard all lower-order terms 3n n  O(n2+n)  O(n2) (n2 log n)/ n  O(n2 log n+n)  O(n2 log n)

42 Digression 2. References/pointers
Java objects often refer to other objects: age name ppsn Fred 37 328723F class Person { Person f = new Person(); int age; f.age = 37; String name; f.name = “Fred”; String ppsn; f.ppsn = “328723F”; } These referred objects aren’t literally “inside” the object, but it’s easy to visualize the object this way, and it doesn’t cause any confusion. A pedant might draw the following diagram instead: age name ppsn arrows mean “refers to object” 37 Fred 328723F

43 References, con’t In some cases, these more accurate drawings can help clear up some confusion Person people[] = new Person[2]; Person f = new Person(); f.age = 37; f.name = “Fred”; f.ppsn = “328723F”; people[0] = f; people[1] = f; people[0].name = “Joe”; System.out.println(“First person’s is ” + people[1].name); age name ppsn people[0] people[1] 37 Fred 328723F

44 Make sure you understand such a beast!
Reference’s con’t Returning to our Linked-List diagrams… class Node { Node next; Object element; } Node head = new Node(); // 1 head.element = “Rome”; head.next = new Node(); // 2 head.next.element = “Seattle”; head.next.next = new Node(); // 3 head.next.next.element = “Toronto”; head.next.next.next = null; this code generates this list Make sure you understand such a beast!

45 Deque = Double-Ended Queues
A double-ended queue, or deque, supports insertion and deletion from the front and back. The Deque Abstract Data Type insertFirst(e): Insert e at the deginning of deque. insertLast(e): Insert e at end of deque removeFirst(): Removes and returns first element removeLast(): Removes and returns last element first() returns first element last() returns last element size() returns number of elements isEmpty() is this deque empty?

46 Implementing Stacks & Queues with Deques
Stacks with Deques: Queues with Deques:

47 The Adaptor Pattern “Patterns” are recurring typical solutions to software design problems (see Section 2.6) Programming languages don’t provide constructs that support for patterns (whereas they do provide constructs supporting modularity, encapsulation, abstraction, …) Using a deque to implement a stack or queue is an example of the adaptor pattern. An adaptor pattern means that you implement a class by using methods of another class (usually giving them other, more specialized names) In general, adaptor classes specialize more generic classes Two such applications: Specialize a general class by changing some methods. Ex: implementing a stack with a deque. Specialize the types of objects used by a general class. Ex: Defining an IntegerArrayStack class that adapts ArrayStack to only store integers.

48 Implementing Deques with Doubly Linked Lists
Deletions at the tail of a singly linked list cannot be done in constant time (recall slide 32) To implement a deque, we use a doubly linked list. with special header and trailer nodes A node of a doubly linked list has a next and a prev link. It supports the following methods: setElement(Object e) setNext(Object newNext) setPrev(Object newPrev) getElement() getNext() getPrev() By using a doubly linked list, all the methods of a deque run in O(1) time. head tail class DLNode { Object element; DLNode next; DLNode prev; } insert delete    

49 Implementing Deques with Doubly Linked Lists (cont.)
When implementing a doubly linked lists, we add two special nodes to the ends of the lists: the header and trailer nodes. The header node goes before the first list element. It has a valid next link but a null prev link. The trailer node goes after the last element. It has a valid prev reference but a null next reference. NOTE: the header and trailer nodes are sentinel or “dummy” nodes because they do not store elements. Here’s a diagram of our doubly linked list:

50 Implementing Deques with Doubly Linked Lists (cont.)
Here’s a visualization of the code for removeLast(). 1. start 2. Slide references 3. done (see page 169 for more examples)

51 Linked Lists - Summary Linked lists are an extremely flexible, very general idea. Lead to efficient (time + space) implemented of queues, stacks Also, often much simpler (compared to, e.g., Q circular array) Basic idea -- design a Node class that holds the data element(s) as well as references to other (previous, next, …) Nodes as needed. The trick to successful implementation is to draw lots of “boxes and arrows” diagrams to make sure you understand in detail how all the Node references should be manipulated

52 Lectures 7 - 11 -- Summary Abstract data types
Clearly separating specification (interface) from implementation (class) Three simple ADTs stack (LI-FO), queue (FI-FO), deque (LorF-IorO) Two implementation strategies for storing lists arrays (simpler, fixed capacity) linked lists (tricker, ‘infinite’ capacity)


Download ppt "Stacks, Queues, Linked Lists, Deques"

Similar presentations


Ads by Google