0% found this document useful (0 votes)
25 views

W4 QueueAndStack

The document provides information about queues and stacks. It defines queues as first-in first-out (FIFO) data structures where elements are added to the rear and removed from the front. Stacks are defined as last-in first-out (LIFO) structures where elements are added and removed from the top. The document discusses various queue and stack operations like add, remove, peek and provides examples of implementations using linked lists and arrays.

Uploaded by

Aimat Kulmakhan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

W4 QueueAndStack

The document provides information about queues and stacks. It defines queues as first-in first-out (FIFO) data structures where elements are added to the rear and removed from the front. Stacks are defined as last-in first-out (LIFO) structures where elements are added and removed from the top. The document discusses various queue and stack operations like add, remove, peek and provides examples of implementations using linked lists and arrays.

Uploaded by

Aimat Kulmakhan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 53

INTRODUCTION TO Week 4: Queue & Stack

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 1: The queue concept


QUEUE OPERATIONS
1) Add/enqueue – insert a given element at the back of the queue.

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.

Figure 4: Peek operation

4) Size – return the number of elements in the queue.


QUEUE OPERATIONS
Example:
Given queue Q with list of operations as below. Illustrate the queue operations step by step:
Q.add(green), Q. add(blue), Q.remove( ), Q.add (red), frontItem = Q.first( ),
lastItem = Q.last(), Q.remove( ), Q.remove().
1. Q.add(green),
2. Q. add(blue),
3. Q.remove( ),
4. Q.add (red),
5. frontItem = Q.first( ),
6. lastItem = Q.last(),
7. Q.remove( ),
8. Q.remove().
QUEUE USING:
LINKED IMPLEMENTATION
 Queue Program:
 Definitions of data structure and functions prototype for queue operations: A Queue
Interface
20 public Object remove();
21
22 /**
1 /** 23 * Removes and returns the element at the front of this queue.
2 * The <code>Queue</code> interface specifies the basic operations 24 *
3 * of a first-in-first-out (FIFO) containers. 25 * @return the element at the front of this queue.
4 */ 26 * @throws IllegalStateException if this queue is empty
5 public interface Queue { 27 */
6 28 public Object size();
7 /** 29
8 * Adds the specified element to the back of this queue and remove the element at the front of 30 /**
this queue. 31 * Returns the number of elements in this queue.
9* 32 *
10 * @param object the element to be added to this queue. 33 * @return the number of elements in this queue.
11 */ 34 */
12 public void first(Object object); 35
13 36 public void add();
14 /** 37
15 * Returns the element at the front of this queue. 38 /**
16 * 39 * Adds the specified element to the back of this queue.
17 * @return the element at the front of this queue. 40 *
18 * @throws IllegalStateException if this queue is empty 41 * @param object the element to be added to this queue.
19 */ 42 */
QUEUE USING:
LINKED IMPLEMENTATION
 The LinkedQueue class

public class LinkedQueue implements Queue {


private Node head = new Node(null);
private int size;

Private static class Node {


Object object;
Node prev=this, next=this;

Node(Object object, Node prev, Node next) {


this.object=object;
this.prev=prev;
this.next=next;
}

}
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:

public class TestLinkedQueue {


public static void main(String[] args) {
Queue kids = new LinkedQueue;
kids.add("Ahmed");
kids.add("Ali");
kids.add("Andy");
kids.add("Sara");
}
}
CIRCULAR QUEUE
When the queue reaches the end of the array, it “wraps around” and the rear of the
queue starts from index 0. The figure below demonstrates the situation. Enqueue (“P”),
will result at rear

14
CIRCULAR QUEUE

Dequeue()
will result in

15
CIRCULAR QUEUE
public Object getHead(){
if(count == 0) throw new ContainerEmptyException();
else return array[front];
}

public void enqueue(Object obj){


if(count == size) throw new ContainerFullException();
else {
array[rear] = obj;
rear = (rear + 1) % size;
count++;
}
}
public Object dequeue(){
if(count == 0)throw new ContainerEmptyException();
else {
Object obj = array[front];
front = (front + 1) % size; //% is ‘mod’
count--; //count the element
return obj;
}
}

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.

• Priority queue requires its elements to be prioritized

• 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:

PriorityQueue(int initialCapacity, Comparator<? super E> comparator)


PriorityQueue(SortedSet<? extends E> c)
Comparator<? super E> comparator()
17
ABSTRACT DATA
TYPE (ADT):

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.

Push stack operation


STACK OPERATIONS
Pop – if the stack not empty, remove the top element of the stack and return it to the
user.

Fig. 3: Pop stack operation


STACK OPERATIONS
Peek – if the stack not empty, copies the element at the top of the stack; return the
data in the top element to the user but does not delete it.

Fig. 4: Peek operation


STACK TEST CLIENT
Read strings from standard input.
 If string equals "-", pop string from stack and print.
 Otherwise, push string onto stack.
Using push and pop write the following statement. to be or not to - be - - that - - - is. % java StackOfStrings
to be not that or be
public static void main(String[] args) {
StackOfStrings stack = new StackOfStrings();
while (!StdIn.isEmpty()) {
String s = StdIn.readString();
if (s.equals("-")) StdOut.print(stack.pop());
else stack.push(s);
}
}
STACK: LINKED-LIST
REPRESENTATION
Maintain pointer to first node in a
linked list; insert/remove from front.
\\save item to return
String item = first.item;
\\delete first node
first = first.next;

return saved item


STACK: ARRAY
IMPLEMENTATION
public class FixedCapacityStackOfStrings{
private String[] s;
private int N = 0;
public FixedCapacityStackOfStrings (int capacity) { \\cheat (stay tuned)
s = new String[capacity]; }
public boolean isEmpty() {
return N == 0; }
public void push (String item) {
s[N++] = item; }
public String pop() {
return s[--N]; }
}
STACK: ARRAY
IMPLEMENTATION
Overflow and underflow.
・ Underflow: throw exception if pop from an empty stack.
・ Overflow: use resizing array for array implementation.
Null items. Allow null items to be inserted.
EXAMPLE
Given stack S with list of operations as below. Illustrate the stack operations step by step:
S.push (green), S.push (blue), S.pop( ), S.push(red), topItem = S.peek( ), S.pop( ), S.pop( )
1. S.push (green),
2. S.push (blue),
3. S.pop( ),
4. S.push(red),
5. topItem =
S.peek( ),
6. S.pop( ),
7. S.pop( )
STACK USING ARRAY-BASED
IMPLEMENTATION
Declarations of data structure and functions prototype for Stack operations in a
Header File.

<<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

public class ArrayStack implements Stack {


private Object[] a;
private int size;
}
• The implementations of the class’s member functions are included at this point in the implementation file.

Fig. 6: Conceptual & physical stack implementation


STACK USING ARRAY-BASED
IMPLEMENTATION
o Create Stack
 Create stack initialize the stack pointer (i.e. top) to NULL, this indicates top as the new empty stack.
 Function definition:
public ArrayStack(int capacity) {
a = new Object[capacity];
}

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.

public void push(Object object) {


if (size == a.length) resize();
a[size++] = object;
}
o Resize an array
// rebuild the array, doubling its size
private void resize() {

Object[] aa = a;

a = new Object[2*aa.length];

System.arraycopy(aa, 0, a, 0, size);
}
STACK USING ARRAY-BASED
IMPLEMENTATION
o Pop

// retrieves and removes the top of a stack


public Object pop() {
if (size == 0) throw new IllegalStateException("stack is empty");
Object object = a[--size];
a[size] = null;
return object;
}
STACK USING ARRAY-BASED
IMPLEMENTATION
o Peek
Function definition:

public Object peek() {


if (size == 0) throw new IllegalStateException("stack is empty");
return a[size-1];
}
STACK USING ARRAY-BASED
IMPLEMENTATION
Implementation: Testing the ArrayStack class
public class Test ArrayStack {
public static void main (String[] args) { crates.push(“WALNUTS”);
Stack crates = new ArrayStack(4); crates.push(“ALMOND”);
crates.push(“CARROTS”); System.out.println(“crates.size(): “ + crates.size() +
crates.push(“ORANGES”);
“\tcrates.peek(): “ + crates.peek());
crates.push(“APPLE”);
System.out.println(“crates.pop(): “ + crates.pop());
crates.push(“PICKLES”);
System.out.println(“crates.pop(): “ + crates.pop());
crates.push(“BANANAS”);
System.out.println(“crates.pop(): “ + crates.pop());
System.out.println(“crates.size(): “ + crates.size() +
System.out.println(“crates.pop(): “ + crates.pop());
“\tcrates.peek(): “ + crates.peek());
System.out.println(“crates.pop(): “ + crates.pop());
System.out.println(“crates.pop(): “ + crates.pop());
System.out.println(“crates.pop(): “ + crates.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:

Infix: A + B the operator comes between two operands.


Prefix: +AB the operator comes before the two operands.
Postfix: AB+ the operator comes after its two operands.
STACK APPLICATION:
POSTPONING DATA USAGE
 How to convert INFIX expression to POSTFIX and PREFIX?
 To calculate INFIX expression requires priority like ()*/ etc., whereas POSTFIX and PREFIX are
not.
 Evaluate postfix expression – Stack
Example:
Infix form: 2+5*3-1
Convert to postfix: 253*+1–
INFIX PREFIX POSTFIX
A+B*C +A*BC ABC*+
(A+B)/(C-D)
(A+B)*C
A/B-C/D
A+B-C*D
STACK APPLICATION:
POSTPONING DATA USAGE
EVALUATE ARITHMETIC STATEMENT
1. Initialize an empty stack.
2. Repeat the following until the end of the expression is encountered:
2.1 Get next token (constant, variable, arithmetic operator) in
the postfix expression.
2.2 If token is an operand, push it onto the stack.
If it is an operator, then
i. Pop top two values from the stack.
IF stack does not contain two items, error due to a malformed postfix. Evaluation terminated.
ELSE
ii. Apply the operator to these two values.
iii. Push the resulting value back onto the stack.

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

1. Read infix expression as input.


2. If input is operand, output the operand.
3. If input is an operator +, -, *, /, then
pop and output all operators of >= precedence. Push operator.
4. If input is (, then push.
5. If input is ), then
pop and output all operators until you see a ( on the stack.
pop the ( without output.
6. If no more input then pop and output all operators on stack.
STACK APPLICATION:
POSTPONING DATA USAGE
 Example: 2 * 3 + (4 - 2) convert to Postfix
Output Stack Description
STACK APPLICATION:
POSTPONING DATA USAGE
 Converting Expression from Infix to Prefix using STACK
It is a bit trickier algorithm, in this algorithm we first reverse the input expression so that a+b*c
will become c*b+a and then we do the conversion and then again the output string is reversed.
Doing this has an advantage that except for some minor modifications the algorithm for Infix-
>Prefix remains almost same as the one for Infix->Postfix.
 Algorithm
1. Reverse the input string.
2. Examine the next element in the input.
3. If it is operand, add it to output string.
4. If it is Closing parenthesis, push it on stack
STACK APPLICATION:
POSTPONING DATA USAGE
5. If it is an operator, then
i. If stack is empty, push operator on stack.
ii. If the top of stack is closing parenthesis, push operator on stack.
iii. If it has same or higher priority than the top of stack, push operator on stack.
iv. Else pop the operator from the stack and add it to output string, repeat step 5.
6. If it is a opening parenthesis, pop operators from stack and add them to output string until a closing
parenthesis is encountered. Pop and discard the closing parenthesis.
7. If there is more input go to step 2
8. If there is no more input, pop the remaining operators and add them to output string.
9. Reverse the output string.
STACK APPLICATION:
POSTPONING DATA USAGE
Example
Convert 2*3/(2-1)+5*(4-1) to Prefix form: Reversed Expression: )1-4(*5+)1-2(/3*2

Input Stack Output


) )
1 ) 1
- )- 1
4 )- 14
( Empty 14-
* * 14-
5 * 14-5 Reverse the output string : +/*23-21*5-41
+ + 14-5*
) +) 14-5* So, the final Prefix Expression is +/*23-21*5-41
1 +) 14-5*1
- +)- 14-5*1
2 +)- 14-5*12
( + 14-5*12-
/ +/ 14-5*12-
3 +/ 14-5*12-3
* +/* 14-5*12-3
2 +/* 14-5*12-32
space Empty 14-5*12-32*/+
EXERCISES
1. Convert the following infix expressions to postfix expressions using the algorithmic method (a
stack diagram):
a) A + B * ( C – D ) / ( E – F )
b) (A – B + C * ( D + E ) ) / F
c) A * ( B + C / ( D – E ) )

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!

You might also like