Data Structures Lakshmish Ramaswamy
Stack Data Structure Last-in-first-out paradigm Supports two operations Push – Insert an element at top Pop – Remove the element at top Can be implemented using ArrayLists or LinkedLists How?
Queue First-in-First-Out Paradigm Many applications Operations Buffer management Job schedulers in OS Operations enqueue Dequeue getFront Can be implemented using ArrayList or LinkedList
Queue
Implementation Using ArrayList/LinkedList enqueue(o) implemented as add(o) Added to the end dequeue() implemented as remove(0) getFirst() implemented as get(0) Problem with ArrayList implementation Every dequeue causes element shifting
Circular Queue Avoids element shifting on enqueue or dequeue Circle with numbered slots Slot numbers increase in clockwise fashion “Capacity” indicates maximum elements queue can hold Two pointers – Front and End -1 indicates empty queue Both pointers move in clockwise direction Wraparound on reaching end
Circular Queue Illustration Front C-1 1 2 End
Circular Queue Implementation public class cirQueue{ Object[] arr; int capacity; int front; int end; public cirQueue(int cpty){ capacity = cpty; arr = new Object[capacity]; front = -1; end = -1;}
Enqueue Method public boolean enqueue(Object o){ if(end == -1){ front = 0; arr[end] = o; return(true);} int newEnd = (end + 1)%capacity; if (newEnd == front) return(false); end = newEnd; return(true); }
Dequeue Method public Object dequeue(){ Object retobj; if(front == -1) return(null); retobj = arr[front]; if(front == end){ front = -1; end = -1;} else{ front = (front+1)%capacity;} return(retobj);}