W4 QueueAndStack
W4 QueueAndStack
ALGORITHMS
Department: Computer science
Course Code: CSS-215
Course Instructor: Asst. Prof. Dr. Mohammed
Ala’anzy
Office no.: G-405
STACKS AND QUEUES
Fundamental data types.
Value: collection of objects.
Operations: insert, remove, iterate, test if empty.
Intent is clear when we insert.
Which item do we remove?
Stack. Examine the item most recently added. LIFO = "last in first out"
Queue. Examine the item least recently added. FIFO = "first in first out 2
ABSTRACT
DATA TYPE
(ADT):
QUEUE
INTRODUCTION
• Queue is linear list in which data can only be inserted at one end, called the rear,
and deleted from the other end, called the front.
• First-In-First-Out (FIFO) concept.
Figure 2: Add
QUEUE OPERATIONS
2) Remove/dequeue – if the queue is not empty, delete and return the element that is at the front of the
queue.
Figure 3: Remove
QUEUE OPERATIONS
3) First – if the queue is not empty, return the element that is at the front of the queue.
}
QUEUE USING:
LINKED IMPLEMENTATION
public void add(Object object) {
head.prev=head.prev.next=new Node(object, head.prev, head);
++size;
}
public Object first() {
if (size()==0) throw new IllegalStateException("queue is empty");
return head.next.object;
}
public boolean isEmpty() {
return size== 0;
}
public Object remove() {
if (size()==0) throw new IllegalStateException("queue is empty");
Object object=head.next.object;
head.next=head.next.next;
head.next.prev=head;
return object;
}
public int size() {
return size;}}
QUEUE USING:
LINKED IMPLEMENTATION
The implementation file begins as follows:
14
CIRCULAR QUEUE
Dequeue()
will result in
15
CIRCULAR QUEUE
public Object getHead(){
if(count == 0) throw new ContainerEmptyException();
else return array[front];
}
16
PRIORITY QUEUES
• Same as ordinary queue except for enqueue or dequeue operation. Instead of insert item at the back or remove
at the front, it refers to their priorities.
• An element that has the same priority as one or more elements in the queue is enqueued after all the elements
with the same priority.
• To accommodate the priority protocol, it includes a constructor for specifying a Comparator, a constructor for
specifying a SortedSet source of elements, and an accessor method for obtaining the elements’ comparator:
STACK
INTRODUCTION
• Stack is a linear list in which data items can only be accessed at one end, called the
top of the stack.
• Data item: Simple data types.
• Last-In–First-Out (LIFO) concept.
STACK OPERATIONS
Basic operations:
Size – return the number of elements in the stack.
Push – add a given element to the top of the stack.
<<interface>>
Stack
+peek() Object
+pop() Object
+push(Object)
+size() int
STACK USING ARRAY-BASED
IMPLEMENTATION
A Stack Interface:
1 /** 22 public Object push();
2 * The <code>Stack</code> interface specifies the basic operations 23
3 * of a last-in-first-out (LIFO) containers. 24 /**
4 */ 25 * Adds the specified element to the top of this stack.
26 *
5 public interface Stack {
27 * @param object the element to be pushed onto this stack.
6 28 */
7 /** 29 public void size(Object object);
8 * Returns a reference to the top element on this stack, leaving 30
9 * the stack unchanged. 31 /**
10 * 32 * Returns the number of elements in this stack.
11 * @return the element at the top of this stack. 33 *
12 * @throws IllegalStateException if this stack is empty. 34 * @return the number of elements in this queue.
13 */ 35 */
14 public Object pop(); 36 public Object peek();
15 37
38 /**
16 /** 39 * Returns the element at the top of this stack.
17 * Removes and returns the element at the top of this stack. 40 *
18 * 41 * @return the element at the top of this stack.
19 * @remove and return the element at the top of this stack. 42 * @throws IllegalStateException if this stack is empty.
20 * @throws IllegalStateException if this stack is empty. 43 */
21 */
STACK USING ARRAY-BASED
IMPLEMENTATION
The implementation file begins as follows:
<< interface >>
Stack
+peek() Object
+pop() Object
+push(Object)
+size() int
ArrayStack
- a: Object[]
- size: int
(methods)
STACK USING ARRAY-BASED
IMPLEMENTATION
An ArrayStack Class
o Empty Stack
Check if stack is empty.
Function definition:
public boolean isEmpty() {
return (size == 0);
}
STACK USING ARRAY-BASED
IMPLEMENTATION
o Push
Adds an item at the top of the stack.
If there is not enough space to insert - overflow state or resize the array size.
Object[] aa = a;
a = new Object[2*aa.length];
System.arraycopy(aa, 0, a, 0, size);
}
STACK USING ARRAY-BASED
IMPLEMENTATION
o Pop
System.out.println(“crates.pop(): “ + crates.pop()); }
System.out.println(“crates.size(): “ + crates.size() +
“\tcrates.peek(): “ + crates.peek());
STACK USING ARRAY-BASED
IMPLEMENTATION
Output:
crates.size(): 5 crates.peek(): BANANAS
crates.pop(): BANANAS
crates.pop(): PICKLES
crates.pop(): APPLE
crates.size(): 2 crates.peek(): ORANGES
crates.size(): 4 crates.peek(): ALMOND
crates.pop(): ALMOND
crates.pop(): WALNUTS
crates.pop(): ORANGES
crates.pop(): CARROTS
java.lang.IllegalStateException: stack is empty
Exception in thread main
STACK APPLICATIONS
Stack applications classified into 4 broad categories:
Reversing data – e.g. reverse a list & convert decimal to binary.
Eg. 26 = 110102
Parsing data – e.g. translate a source program to machine language.
Postponing data usage – e.g. evaluation, transformation.
Backtracking – e.g. computer gaming, decision analysis, expert systems.
STACK APPLICATION:
POSTPONING DATA USAGE
ARITHMETIC STATEMENT
Example:
A * B + C (How computers generate it???)
Arithmetic expression written in INFIX as above example.
However compiler change to POSTFIX/PREFIX for calculating purposes.
Three different formats:
3. When the end of expression encountered, its value is on top of the stack (and, in fact, must be the only value in
the stack).
STACK APPLICATION:
POSTPONING DATA USAGE
TRY THIS: 2 5 3 * + 1 – ?
3
5 5 15 1
2 2 2 2 17 17 16
STACK APPLICATION:
POSTPONING DATA USAGE
public static void main(String[] args) {
char ch;
Stack s; // create stack
double operan1, operan2, value;
System.out.println( “Type postfix expression: “);
while ( ch = System.in.read() && ch != ‘\n’) {
if ( Character.isDigit(ch) ) s.push(ch – 48);
else {
s.pop(operan2);
s.pop(operan1);
switch (ch) {
case ‘+’ : s.push(operan1+operan2); break;
case ‘-’ : s.push(operan1-operan2); break;
case ‘*’ : s.push(operan1*operan2); break;
case ‘/’ : s.push(operan1+operan2); break;
} // end switch
} // end else
} //end while
s.pop(value);
System.out.println(“ = “ + value);
}
STACK APPLICATION:
POSTPONING DATA USAGE
Below is the output:
345*+ = 23.00
345+* = 27.00
34*5+ = 17.00
4321*++ = 9.00
9324+5-*/7+ = 10.00
STACK APPLICATION:
POSTPONING DATA USAGE
Algorithm: Convert infix to postfix
2. Using the algorithmic method (a stack diagram) evaluate the following postfix expressions when
the variables have the following values A is 2, B is 3, C is 4, and D is 5.
a) A B * C – D +
b) A B C + * D –
EXERCISES
Given a reference first to the first node of a null-terminated linked list with at least two
nodes, what does the code fragment below do?
1. Node x = first;
2. while (x.next.next != null) {
3. x = x.next;
4. }
5. x.next = null;
o deletes the first node in the list
o deletes the second node in the list
o deletes the next-to-last node in the list
o deletes the last node in the list
THANK YOU!