Professional Documents
Culture Documents
3 Stack Queue
3 Stack Queue
Stack Overview
* Stack ADT
■ Basic operations of stack
Pushing, popping etc.
Stack ADT
* Stacks are less flexible
but are more efficient and easy to implement
* Stacks are known as LIFO (Last In, First Out)
lists.
■ The last element inserted will be the first to be
retrieved
Stack and Queue / Slide 5
top
B
top top A
A A
top
Stack and Queue / Slide 6
Implementation of Stacks
Array Implementation
* Need to declare an array size ahead of time
* Associated with each stack is TopOfStack
■ for an empty stack, set TopOfStack to -1
* Push
■ (1) Increment TopOfStack by 1.
■ (2) Set Stack[TopOfStack] = X
* Pop
■ (1) Set return value to Stack[TopOfStack]
■ (2) Decrement TopOfStack by 1
* These operations are performed in very fast in
constant time
Stack and Queue / Slide 8
Stack class
abstract class Stack {
private int stackSize; // max stack size
private int top; // current top of stack
private int values[]; // item array
Stack class
* Attributes of Stack
■ stackSize: the max size of stack
■ top: the index of the top element of stack
■ values[]: an array which stores elements of stack
* Operations of Stack
■ isEmpty: return true if stack is empty, return false otherwise
■ isFull: return true if stack is full, return false otherwise
■ peek: return the element at the top of stack
■ push: add an element to the top of stack
■ pop: delete the element at the top of stack
■ popAll: delete all the data in the stack
Stack and Queue / Slide 10
Create Stack
* The constructor of Stack
■ Allocate a stack array of size.
■ When the stack is full, top will have its maximum value,
i.e. stackSize – 1.
■ Initially top is set to -1. It means the stack is empty.
Push Stack
* void push(int x);
■ Push an element onto the stack
■ If the stack is full, print the error information.
■ Note top always represents the index of the top
element. Before pushing an element, increment
top.
public void push(int x) {
if (isFull())
System.out.println("Error: the stack is full.“);
else
values[++top] = x;
}
Stack and Queue / Slide 12
Pop Stack
* int pop()
■ Pop and return the element at the top of the stack
■ If the stack is empty, print the error information. (In
this case, the return value is useless.)
■ Don’t forget to decrement top
Peek Stack
* int peek()
■ Return the top element of the stack
■ Unlike pop, this function does not remove the top
element
Using Stack
public static void main(String[] args) {
Stack s = new Stack(5);
s.push(5);
s.push(6);
s.push(-3);
s.push(-8);
System.out.println("Top: “+ s.peek());
s.pop();
System.out.println("Top: “+ s.peek());
while (!s.isEmpty()) {
//print each element and delete from stack
System.out.println(“Next top: “+ s.pop());
}
}
Implementation based on Linked
Stack and Queue / Slide 16
List
* Now let us refine the Node class and use to implement a stack
based on a linked list
class Node {
private int value;
private Node next;
List
class StackRefBased{
private Node top;
public StackRefBased() {top = null;} // constructor
public boolean isEmpty() {return top == null;}
public void push(int x) { top = new Node(x, top); }
public int pop() {
if (!isEmpty()) {
Node temp = top;
top = top.getNext();
return temp.getValue();
}
else {
System.out.println("Error: the stack is empty.“);
return -1;
}
}
Note: the stack
public int peek() { implementation based
if (!isEmpty()) {
return top.getValue();
on a linked list will
} never be full.
else {
System.out.println("Error: the stack is empty.“);
return -1;
}
}
}
Stack and Queue / Slide 18
Queue Overview
* Queue ADT
■ Basic operations of queue
Enqueue, dequeue, etc.
* Implementation of queue ADT
■ Array
■ Linked list
Stack and Queue / Slide 22
Queue ADT
* Like a stack, a queue is another form of
restricted list. However, with a queue,
insertion is done at one end, while deletion is
performed at the other end.
* Accessing the elements of queue follows a
First In, First Out (FIFO) order.
■ Like customers standing in a check-out line in a
store, the first customer in is the first customer
served.
Stack and Queue / Slide 23
Remove Insert
(Dequeue) front rear (Enqueue)
Queue Implementation of
Stack and Queue / Slide 25
Array
* There are several different algorithms to
implement Enqueue and Dequeue operations
* Naïve way
■ When enqueuing, the front index is always fixed
and the rear index moves forward in the array.
rear rear rear
3 3 6 3 6 9
Array
* Naïve way
■ When enqueuing, the front index is always fixed
and the rear index moves forward in the array.
■ When dequeuing, the element at the front of the
queue is removed. Move all the elements after it by
one position. (Inefficient!!!)
rear rear rear = -1
6 9 9
Array
* Better way
■ When an item is enqueued, make the rear index move
forward.
■ When an item is dequeued, the front index moves by
one element towards the back of the queue (thus
removing the front item, so no copying to
neighboring elements is needed).
Array
* Using a circular array
* When an element moves past the end of a circular
array, it wraps around to the beginning, e.g.
■ OOOOO7963 4OOOO7963 (after Enqueue(4))
■ After Enqueue(4), the rear index moves from 3 to 4.
Stack and Queue / Slide 29
Stack and Queue / Slide 30
Empty or Full?
* Empty queue
■ rear = front - 1
* Full queue?
■ the same!
* Possible Solutions:
■ Use a boolean variable to say explicitly whether the
queue is empty or not
■ Make the array of size n+1 and only allow n
elements to be stored
■ Use a counter of the number of elements in the
queue
Stack and Queue / Slide 31
Queue Class
* Attributes of Queue
■ front/rear: front/rear index
■ counter: number of elements in the queue
■ maxSize: capacity of the queue
■ values[]: an array which stores elements of the queue
* Operations of Queue
■ isEmpty: return true if queue is empty, return false otherwise
■ isFull: return true if queue is full, return false otherwise
■ enqueue: add an element to the rear of queue
■ dequeue: delete the element at the front of queue
■ deueueAll: destroy all queue the data
Stack and Queue / Slide 33
Create Queue
* Queue(int size)
■ Allocate a queue array of size.
■ front is set to 0, pointing to the first element of the array
■ rear is set to -1. The queue is empty initially.
Enqueue
public void enqueue(int x) {
if (isFull()) {
System.out.println("Error: the queue is full.“);
}
else {
// calculate the new rear position (circular)
rear = (rear + 1) % maxSize;
// insert new item
values[rear] = x;
// update counter
counter++;
}
}
Stack and Queue / Slide 36
Dequeue
public int dequeue() {
if (isEmpty()) {
System.out.println("Error: the queue is empty.“);
}
else {
// retrieve the front item
int x = values[front];
// move front
front = (front + 1) % maxSize;
// update counter
counter--;
return x;
}
}
Stack and Queue / Slide 37
Using Queue
List
}
Stack and Queue / Slide 41
Enqueue
public void enqueue(int x) {
Node newNode = new Node(x,NULL);
if (isEmpty()) {
front = newNode;
rear = newNode;
}
else {
rear
rear.setNext(newNode);
rear = newNode; 8 5
}
counter++; rear
}
8 5
newNode
Stack and Queue / Slide 42
Dequeue
public int dequeue() {
if (isEmpty()) {
System.out.println(“Error: the queue is empty.“);
return -1;
}
else {
int x = front.getValue();
front = front.getNext();
counter--;
return x;
}
} front
3 8 5
front
8 5
Stack and Queue / Slide 43
DequeueAll
Result
* Queue implemented using linked list will be
never full
Exercises
1) Express (3 + 5) * (7 – 2) in Polish notation and
use stack to evaluate the answer
2) Write method balancedBracket that use
stack to check whether a given string has
balanced brackets.
3) Write method postfixEvaluator that use stack
to evaluate a given postfix expression.
4) Write method isPalindrome that use stack
and queue to determine whether a given
string is a palindrome.