Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen
Stacks and Queues Stacks and Queues
Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen
What is a Stack?
What is a Stack?
Stores a set of elements in a particular order Stores a set of elements in a particular order Accessed in Last
Accessed in Last- -In In- -First First- -Out (LIFO) fashion Out (LIFO) fashion Real life examples:
Real life examples:
• • Pile of books Pile of books
•
• PEZ dispenser PEZ dispenser
•
• Cup trays in cafeteria Cup trays in cafeteria
CS examples: program execution stack, CS examples: program execution stack,
parsing/evaluating expressions parsing/evaluating expressions
Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen
Stack Abstract Data Type Stack Abstract Data Type push(
push(o o): insert ): insert o o on top of stack on top of stack pop( ): remove object from top of stack pop( ): remove object from top of stack top( ): look at object on top of stack (but top( ): look at object on top of stack (but
don’t remove) don’t remove)
size( ): number of objects on the stack size( ): number of objects on the stack isEmpty
isEmpty( ): does (size = = 0)? ( ): does (size = = 0)?
Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen
Java Interface for Stack ADT Java Interface for Stack ADT
public interface Stack { public interface Stack {
public
public int int size(); size();
public
public boolean boolean isEmpty(); isEmpty ();
public Object top() throws public Object top() throws
StackEmptyException StackEmptyException; ;
public void push (Object element);
public void push (Object element);
public Object pop() throws public Object pop() throws
StackEmptyException StackEmptyException; ; } }
Array
Array- -based Stack Implementation based Stack Implementation Allocate array of some size
Allocate array of some size
• • Maximum # of elements in stack Maximum # of elements in stack Bottom stack element stored at index 0 Bottom stack element stored at index 0 first
first index tells which element is the top index tells which element is the top increment
increment first first when element pushed, when element pushed, decrement when
decrement when pop’d pop’d
Array
Array- -based Implementation based Implementation
public class
public class ArrayStack ArrayStack implements Stack { implements Stack { private Object[] S;
private Object[] S;
private
private int int topIndex topIndex = = - -1; 1;
public void push(Object
public void push(Object obj obj) throws ) throws StackFull StackFull { { if (size() == S.length)
if (size() == S.length) throw new
throw new StackFull(“full StackFull(“full”); ”);
S[++topIndex
S[++topIndex] = ] = obj obj; } ; } public Object pop() throws
public Object pop() throws StackEmpty StackEmpty { { if (
if (isEmpty isEmpty()) ()) throw new
throw new StackEmpty(“empty StackEmpty(“empty”); ”);
Object
Object elem elem = S[topIndex = S[topIndex]; ];
S[topIndex
S[topIndex-- --] = null; ] = null;
return return elem elem; } ; } }
}
Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen
Analysis Analysis
Each operation is
Each operation is O O(1) running time (1) running time
•
• Independent of number of items in stack Independent of number of items in stack
•
• push, pop, top, size, push, pop, top, size, isEmpty isEmpty Space can be
Space can be O O( (n n) or may be much more ) or may be much more
•
• depends if depends if n n is known at initialization time is known at initialization time
Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen
Linked List Stack Implementation Linked List Stack Implementation Benefits
Benefits
•
• Avoids maximum stack size restriction Avoids maximum stack size restriction
• • Only allocates memory for stack elements Only allocates memory for stack elements actually used
actually used How
How
• • Allocate a node for each stack element Allocate a node for each stack element
• • Nodes are chained together by reference to Nodes are chained together by reference to next node in the chain
next node in the chain
Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen
Linked List Node Linked List Node
public class Node { public class Node {
private Object element;
private Object element;
private Node next;
private Node next;
public Node(Object e, Node n) { public Node(Object e, Node n) {
element = e; next = n; } element = e; next = n; }
…
… } }
Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen
Linked List Stack Implementation Linked List Stack Implementation
public class
public class LinkedStack LinkedStack implements Stack { implements Stack { private Node top = null;
private Node top = null;
private
private int int size = 0; size = 0;
public void push(Object public void push(Object elem elem) { ) {
Node v = new Node();
Node v = new Node();
v.setElement(elem v.setElement(elem); );
v.setNext(top v.setNext(top); );
top = v;
top = v;
size++; } size++; }
public Object pop() throws
public Object pop() throws StackEmpty StackEmpty { { if ( if (isEmpty isEmpty()) throw new ()) throw new
StackEmpty(“empty StackEmpty(“empty”); ”);
Object temp =
Object temp = top.getElement top.getElement(); ();
top =
top = top.getNext top.getNext(); ();
size size -- --; ; return temp; } return temp; } }
}
Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen
Analysis Analysis
All stack functions still All stack functions still O O(1) (1)
•
• push, pop, top, size, isEmpty push, pop, top, size, isEmpty
Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen
What is a Queue What is a Queue
Stores a set of elements in a particular order Stores a set of elements in a particular order Accessed in First
Accessed in First- -In In- -First First- -Out (FIFO) Out (FIFO) fashion
fashion
Real life examples:
Real life examples:
•
• Waiting in line at cafeteria Waiting in line at cafeteria
•
• Waiting on hold for technical support Waiting on hold for technical support CS Example: Buffered I/O
CS Example: Buffered I/O
Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen
Queue ADT Queue ADT enqueue(
enqueue(o o): Insert object ): Insert object o o at at rear rear of queue of queue dequeue
dequeue( ): remove object from ( ): remove object from front front of of queue
queue
size( ): number of elements size( ): number of elements isEmpty
isEmpty( ): size == 0? ( ): size == 0?
front( ): look at object at front of queue front( ): look at object at front of queue
Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen
Queue Interface in Java Queue Interface in Java
public interface Queue { public interface Queue {
public
public int int size(); size();
public
public boolean boolean isEmpty isEmpty(); ();
public Object front() throws
public Object front() throws QueueEmpty QueueEmpty; ; public void
public void enqueue enqueue (Object element); (Object element);
public Object
public Object dequeue dequeue() throws () throws QueueEmpty QueueEmpty; ; }
}
Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen
Array
Array- -based Queue Implementation based Queue Implementation
Array of fixed size Array of fixed size
Index array element for front and rear of Index array element for front and rear of
queue queue
Indices “wrap around” when they cross end Indices “wrap around” when they cross end
of array of array
Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen
Array Queue Implementation Array Queue Implementation
public class
public class ArrayQueue ArrayQueue implements Queue { implements Queue { private Object[] Q;
private Object[] Q;
private
private int int size=0; size=0;
private
private int int front=0, rear = 0; front=0, rear = 0;
public void
public void enqueue(Object enqueue(Object o) { o) { if (size( ) ==
if (size( ) == Q.length Q.length) throw ) throw new QueueFull(“full new QueueFull(“full”); ”);
Q[rear] = o;
Q[rear] = o;
rear = (rear + 1) %
rear = (rear + 1) % Q.length Q.length; ; size++;
size++;
} }
List Queue Implementation List Queue Implementation Head and tail node references for front and Head and tail node references for front and
rear of queue rear of queue
Insert at tail, remove from head Insert at tail, remove from head
• • Remove from tail too slow for singly linked list Remove from tail too slow for singly linked list
—Updating tail reference with new tail takes — Updating tail reference with new tail takes full traversal
full traversal
• • So use tail of list for rear of queue So use tail of list for rear of queue
List Queue Implementation List Queue Implementation
public class
public class ListQueue ListQueue implements Queue { implements Queue {
private Node head = null;
private Node head = null;
private Node tail = null;
private Node tail = null;
private
private int int size = 0; size = 0;
. . . . . . }
}
Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen
List Queue List Queue
public void
public void enqueue(Object enqueue(Object obj) { obj ) { Node node = new
Node node = new Node(obj Node(obj, null); , null);
if (size == 0) if (size == 0) head = node;
head = node;
else else
tail.setNext(node tail.setNext(node); );
tail = node;
tail = node;
size++;
size++;
}
} public Object
public Object dequeue dequeue() { () { Object
Object obj obj = head.getElement = head.getElement(); ();
head =
head = head.getNext head.getNext(); ();
size size-- --; ;
if (size == 0) if (size == 0) tail = null tail = null return return obj obj; ; }
}
Johns Hopkins Department of Computer ScienceCourse 600.226: Data Structures, Professor: Jonathan Cohen
Analysis Analysis
All queue operations are All queue operations are O O(1) (1)
• • size( ), isEmpty size( ), isEmpty( ) ( )
•
• enqueue( ), enqueue ( ), dequeue dequeue( ), front( ) ( ), front( )
Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen
Double
Double -ended Queue - ended Queue
Sometimes called “
Sometimes called “deque deque” ( ” (dek dek) ) Similar to stack and queue Similar to stack and queue
•
• Allows insertion and removal at both ends of Allows insertion and removal at both ends of the queue
the queue
•
• Stack or queue is easily implemented using a Stack or queue is easily implemented using a deque
deque
Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen
Deque Deque ADT ADT insertFirst(
insertFirst(e e) : insert element at front ) : insert element at front insertLast(
insertLast(e e) : insert element at rear ) : insert element at rear removeFirst
removeFirst( ) : remove first element ( ) : remove first element removeLast
removeLast( ) : remove element at rear ( ) : remove element at rear first( ) : examine first element
first( ) : examine first element last( ) : examine last element last( ) : examine last element size(
size(e e) : number of elements in ) : number of elements in deque deque isEmpty
isEmpty( ) : size == 0? ( ) : size == 0?
Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen
Doubly Linked List Doubly Linked List
Singly linked list inefficient for removing Singly linked list inefficient for removing
from tail from tail Has
Has prev prev reference as well as next reference reference as well as next reference Can use
Can use sentinel sentinel nodes to reduce the special nodes to reduce the special cases
cases
• • node has no element, just next or prev node has no element, just next or prev reference
reference
Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen
Deque
Deque Implementation Implementation
public class
public class MyDeque MyDeque implements Deque implements Deque { { DLNode
DLNode header, trailer; header, trailer;
int int size; size;
public
public MyDeque MyDeque() { () { header = new
header = new DLNode DLNode(); ();
trailer = new
trailer = new DLNode DLNode(); ();
header.setNext(trailer header.setNext(trailer); );
trailer.setPrev(header trailer.setPrev(header); );
size = 0;
size = 0;
} }
Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen
Deque
Deque Implementation Implementation
public void
public void insertFirst(Object insertFirst(Object o) { o) { DLNode
DLNode second = header.getNext second = header.getNext(); ();
DLNode
DLNode first = first = new
new DLNode(o,header DLNode(o,header, second); , second);
second.setPrev(first second.setPrev(first); );
header.setNext(first header.setNext(first); );
size++;
size++;
}
} Could be null if no sentinels
(trailer could also be null)
Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen
Deque
Deque (no sentinels) (no sentinels)
public void
public void insertFirst(Object insertFirst(Object o) { o) { DLNode
DLNode second = header; second = header;
DLNode
DLNode first = new DLNode(o first = new DLNode(o, null, second); , null, second);
header = first;
header = first;
if (second == null) if (second == null) trailer = first;
trailer = first;
else else
second.setPrev(first second.setPrev(first); );
size++;
size++;
} }
Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen