1 stacks, queues & deques csc212. 2 stacks & queues stack: last in first out (lifo). –used...
Post on 20-Dec-2015
232 views
TRANSCRIPT
1
Stacks, Queues & Deques
CSC212
2
Stacks & Queues
• Stack: Last In First Out (LIFO).– Used in procedure calls, to compute arithmetic
expressions etc.
• Queue: First In First Out (FIFO).– Used in operating systems, simulations etc.
• Priority Queues: Highest priority item is served first.– Used in operating systems, printer servers etc.
3
Stack (Linked Implementation)
TOP
4
ADT Stack: Specification
Elements: The elements are of a variable type <Type>. In a linked implementation an element is placed in a node.
public class Node<T> extends Object {public T data;public Node<T> next;public Node () { data = null; next = null; }public Node (T val) { data = val; next = null; }
}
5
ADT Stack: Specification
Structure: the elements are linearly arranged, and ordered according to the order of arrival, most recently arrived element called top.
Domain: the number of elements in the stack is bounded therefore the domain is finite. Type of elements: Stack
6
ADT Stack: Specification
Operations: All operations operate on a stack S.1. Method Push (Type e)
requires: Stack S is not full. input: Type e.results: Element e is added to the stack as its most recently added elements. output: none.
2. Method Pop (Type e)requires: Stack S is not empty. input: results: the most recently arrived element in S is removed and its value assigned to e. output: Type e.
3. Method Empty (boolean flag)input: results: If Stack S is empty then flag is true, otherwise false. output: flag.
7
ADT Stack: Specification
Operations:
4. Method Full (boolean flag).
requires: input: .
results: If S is full then Full is true, otherwise Full is false. output: flag.
8
ADT Stack (Linked Implementation)
TOP
DataElement
Pointer
A LinkedImplementation of the Stack.
9
ADT Stack (Linked Implementation)
public class LinkStack<T> { private Node<T> top; /* Creates a new instance of LinkStack */ public LinkStack() { top = null; } public boolean empty(){ return top == null; }
10
ADT Stack (Linked Implementation)
public boolean full(){ return false; }public void push(T e){ Node<T> tmp = new Node(e); tmp.next = top; top = tmp; }
11
ADT Stack (Linked Implementation)
public T pop(){ T e = top.data;
top = top.next; return e; }}
12
Stack: Array Implementation
public class ArrayStack<T> { private int maxsize; private int top; private T[] nodes; /** Creates a new instance of ArrayStack */ public ArrayStack(int n) { maxsize = n; top = -1; nodes = (T[]) new Object[n]; }
13
Stack: Array Implementation
public boolean empty(){ return top == -1; } public boolean full(){ return top == maxsize-1; }
14
Stack: Array Implementation
public void push(T e){ nodes[++top] = e; } public T pop(){ return nodes[top--]; }}
15
Applications of Stacks
• Some applications of stacks are:– Balancing symbols.– Computing or evaluating postfix expressions.– Converting expressions from infix to postfix.
16
1. Balancing Symbols
• Expressions: mathematical (a + ((b-c)*d)) or programs have delimiters.
begin {S1 S1S2 {begin S2
S3 S3begin }…. S4end }
endend
17
1. Balancing Symbols
• Delimiters must be balanced. [()] is legal but [(]) illegal.
• A stack can be used to check if the delimiters are balanced.– Read characters from the start of the expression
to the end.– If the token is a starting delimiter, push on to
the stack, if closing delimiter pop the corresponding start delimiter from the stack.
18
1. Balancing Symbols
– If the stack is empty or if the popped symbol does not correspond to the closing symbol: report error.
– If stack is not empty at the end of file report an error.
19
2. Postfix Expressions
• Evaluating Postfix Expressions:– Infix expression: 4.99*1.06+5.99+6.99*1.06– Value 18.69 correct parenthesis used.– Value 19.37 incorrect no parenthesis used.– In postfix form, above expression becomes:
4.99 1.06 * 5.99 + 6.99 1.06*+
Advantage: no brackets are needed and a stack can be used to compute the expression.
20
2. Postfix Expressions
• Example: – infix: 6*(5+((2+3)*8)+3)– postfix: 6 5 2 3 + 8 * + 3 + *.
• Algorithm to compute postfix expression: – Read the postfix expression left to right. When
a number is read push it on the stack; when a operator is read, pop two numbers from the stack and carry out the operation on them, push the result back on the stack.
21
3. Infix to Postfix Conversion
• A stack can also be used to convert an infix expression to postfix expression. (See handout)
• Example: infix expression a + b * c + (d * e + f) * g
to postfix expressiona b c * + d e * f + g * +
See class notes for more examples.
22
Queues
Front
Tail
23
ADT Queue: Specification
Elements: The elements are of a variable type <Type>. In a linked implementation elements are placed in nodes.
public class Node<T> extends Object {public T data;public Node<T> next;
public Node () { data = null; next = null; }
public Node (T val) { data = val; next = null; }
}
24
ADT Queue: Specification
Structure: the elements are linearly arranged, and ordered according to the order of arrival, most recently arrived element is called the tail and least recently arrived element the front or head.
Domain: the number of elements in the queue is bounded therefore the domain is finite. Type of elements: Queue
25
ADT Queue: Specification
Operations:
1. Method Enqueue (Type e)
requires: Queue Q is not full. input: Type e.
results: Element e is added to the queue at its tail. output: none.
2. Method Serve (Type e)
requires: Queue Q is not empty. input:
results: the element at the head of Q is removed and its value assigned to e. output: Type e.
3. Method Length (int length)
input: results: The number of element in the Queue Q is returned. output: length.
26
ADT Queue: Specification
Operations:
4. Method Full (boolean flag).
requires: input:
results: If Q is full then flag is set to true, otherwise flag is set to false. output: flag.
27
ADT Queue (Linked Implementation)
public class LinkQueue <Type> { private Node<Type> head, tail; private int size; /** Creates a new instance of LinkQueue */public LinkQueue() { head = tail = null; size = 0; }
28
ADT Queue (Linked Implementation)
public boolean full() {
return false; } public int length (){ return size; }
29
ADT Queue (Linked Implementation)
public void enqueue (Type e) { if (tail == null){ head = tail = new Node(e); } else { tail.next = new Node(e); tail = tail.next; } size++; }
30
ADT Queue (Linked Implementation)
public Type serve() { Node<Type> tmp; Type x; tmp = head; x = head.data; head = head.next; size--; if (size == 0) tail = null; return x; }}
31
ADT Queue (Array Implementation)
• Array implementation of the queue…a fixed size array is used to store the data elements.
• As data elements are enqueued & served the queue crawls through the array from low to high index values.
• As the queue crawls forward, it also expands and contracts.
32
ADT Queue (Array Implementation)
Head Tail
Head TailAfter one En-queue and one Serve
33
ADT Queue (Array Implementation)
Head Tail
Where to En-queue this?
34
ADT Queue (Array Implementation)
HeadTail
Wrap Round
0 MaxSize-1
35
ADT Queue (Array Implementation)
0 MaxSize - 1
HeadTail
36
ADT Queue (Array Implementaion)
public class ArrayQueue <T> { private int maxsize; private int size; private int head, tail; private T[] nodes; /** Creates a new instance of ArrayQueue */public ArrayQueue(int n) { maxsize = n; size = 0; head = tail = 0; nodes = (T[]) new Object[n]; }
37
ADT Queue (Array Implementation)
public boolean full () { return size == maxsize ? true : false; } public int length () { return size; } public void enqueue(T e) { nodes[tail] = e; tail = (tail + 1) % maxsize; size++; }
38
ADT Queue (Array Implementation)
public T serve () { T e = nodes[head]; head = (head + 1) % maxsize; size--; return e; }}
39
Priority Queue
• Each data element has a priority associated with it.Highest priority item is served first.
• Real World Priority Queues: hospital emergency rooms…most sick patients treated first, events in a computer system, etc.
• Priority Queue can be viewed as:– View 1: Priority queue as an ordered list.
– View 2: Priority queue as a set.
40
ADT Priority Queue
Specification:Elements: The elements are of type PQNode. Each node has
in it a data element of variable type <Type> and priority of type Priority ( which could be int type).
public class PQNode<T> { private T data; private Priority priority; public PQNode<T> next; public PQNode() { next = null; } public PQNode(T e, Priority p) { data = e; priority = p; }
41
ADT Priority Queue
Structure: the elements are linearly arranged, and may be ordered according to a priority value, highest priority element is called the tail and least priority element the front or head.
Domain: the number of nodes in the queue is bounded therefore the domain is finite. Type of elements: PriorityQueue
42
ADT Priority Queue
Operations: 1. Method Enqueue (Type e, Priority p)
requires: PQ is not full. input: e, p.results: Element e is added to the queue according to its priority. output: none.
2. Method Serve (Type e, Priority p)requires: PQ is not empty. input: results: the element at the head of PQ is removed and returned. output: e, p.
3. Method Length (int length)input: results: The number of element in the PQ is returned. output: length.
43
ADT Priority Queue
Operations:
4. Method Full (boolean flag).
requires: input:
results: If PQ is full then flag is set to true, otherwise flag is set to false. output: flag.
44
ADT Priority Queue
el10
el el el el el10 8 7 7 5
Head Tail
Array Implementation
el7
Insert Where?
el10
el10
el8
el7
el5
el7
Head Tail
Linked Implementation
el el
45
ADT Priority Queue (Linked)
public class LinkPQ<T> { private int size; private PQNode<T> head, tail;
/* tail is of no use here. */ public LinkPQ() { head = tail = null; size = 0; } public int length (){ return size; }
46
ADT Priority Queue (Linked)
public int length (){ return size; } public boolean full () { return false; }
47
ADT Priority Queue (Linked)
public void enqueue(T e, int pty) { PQNode<T> p, q, tmp; if ((size == 0) || (pty > head.Priority())) { tmp = new PQNode<T>(e, pty); tmp.next = head; head = tmp; } else { p = head; q = null; while ((p != null) && (p.Priority() > pty)) { q = p; p = p.next; } tmp = new PQNode<T>(e, pty); tmp.next = p; q.next = tmp; } }
48
ADT Priority Queue (Linked)
public T serve (Priority pty){ T e = head.get_data();
pty.set_value(head.get_priority().get_value()); head = head.next; size--; return(e); }}
49
ADT Priority Queue
• Implementations– Array Implementation: Enqueue is O(n), Serve
is O(1).– Linked List: Enqueue is O(n), Serve is O(1).– Heap: Enqueue is O(log n), Serve is O(log n)
Heaps to be discussed later.
50
Double-Ended Queues
• Double ended queue (or a deque) supports insertion and deletion at both the front and the tail of the queue.
• Supports operations: addFirst( ), addLast(), removeFirst( ) and removeLast( ).
• Can be used in place of a queue or a stack.
51
Double-Ended Queues
Operations: (Assume all operations are performed on deque DQ)1. Method addFirst (Type e)
requires: DQ is not full. input: e.results: Element e is added to DQ as first element. output: none.
2. Method addLast (Type e)requires: DQ is not full. input: eresults: Element e is added to DQ as last element. output: none.
3. Method removeFirst (Type e)requires: DQ is not empty. input: none results: Removes and returns the first element of DQ. output: e.
52
Double-Ended Queues
4. Method removeLast (Type e)requires: DQ is not empty. input: none.results: Removes and returns the last element of DQ. output: e.
5. Method getFirst (Type e)requires: DQ is not empty. input: noneresults: Returns the first element of DQ. output: e.
6. Method getLast (Type e)requires: DQ is not empty. input: none results: Returns the last element of DQ. output: e
7. Method size (int x)input: none results: Returns the number of elements in DQ. output: x
53
Double-Ended Queues
8. Method isEmpty (boolean x)input: none results: if DQ is empty returns x as true otherwise false. output: x