L02b ADT Stack and Queue
L02b ADT Stack and Queue
2
1 Abstract Data Type
class Employee {
const int MAX_NUMBER = 500;
private:
String name;
double salary;
public:
double cpf();
…
}
…
Employee * workers = new Employee[100];
4
1.2 Abstract Data Type (ADT) (1/4)
An ADT represent a collection of data together with a
specification of a set of operations (functional
abstraction) on the data
Functional abstraction The specifications indicate what
ADT operations do, not how to implement them
Also does not specify how the data is to be stored
Collection Spec. of a
ADT of data set of
operations
5
1.2 Abstract Data Type (ADT) (2/4)
When a program needs data operations that are not
directly supported by a language, you need to create
your own ADT
You should first design the ADT by carefully specifying
the operations before implementation
6
1.2 Abstract Data Type (ADT) (3/4)
Example: A water dispenser as an ADT
Data: water
Operations: chill, crush, cube,
and isEmpty
Data structure: the internal
structure of the dispenser
Walls: made of steel
The only slits in the walls:
Input: water
Output: chilled water, crushed
ice, or ice cubes.
Crushed ice can be made in many ways.
We don’t care how it was made
8
Eg: Primitive Types as ADTs (1/2)
C++’s predefined data types are ADTs
Representation details are hidden which aids ease of
usage and portability
Examples: int, bool, double
--
||
–
*
int && bool
+
/
++ !
int type with the operations bool type with the operations
(e.g.: --, /) defined on it. (e.g.: &&) defined on it.
9
C++ program
STL
Driver
ADT main.cpp
Specification Implementation
13
ListNode.h (Interface)
class ListNode {
private:
int _item;
ListNode* _next;
public:
ListNode(int);
int content() { return _item; };
friend class List;
};
14
List.h (Interface)
class List{
private:
int _size;
ListNode* _head;
public:
List() {
~List();
_size = 0; void insertHead(int);
_head = NULL; void removeHead();
}; void printAlternate();
int count(int);
int headItem();
};
15
ListNode.cpp (implementation)
#include <iostream>
#include "simpleIntLinkedList.h"
using namespace std;
ListNode::ListNode(int n) {
_item = n;
_next = NULL;
}
16
List.cpp (implementation)
void List::insertHead(int n){
ListNode* aNewNode = new ListNode(n);
aNewNode->_next = _head;
_head = aNewNode;
_size++;
};
void List::removeHead() {
if (_size > 0) {
ListNode* temp = _head;
_head = _head->_next;
delete temp;
_size--;
}
}
17
Driver
#include <iostream>
#include "simpleIntLinkedList.h"
using namespace std;
int main(){
List l;
l.insertHead(123);
l.insertHead(11);
l.insertHead(9);
l.insertHead(1);
l.insertHead(9);
18
Driver
cout << "Print alternating elements: ";
l.printAlternate();
cout << endl;
return 0;
19
1-5 Stacks
Last-In-First-Out (LIFO)
1 Stack ADT: Operations
A Stack is a collection of data that is accessed in
a last-in-first-out (LIFO) manner
Major operations: “push”, “pop”, and “peek”.
item
Pop()
push(item)
Peek()
stack
21
1 Stack ADT: Uses
Calling a function
Before the call, the state of computation is saved on the
stack so that we will know where to resume
Recursion
Matching parentheses
Evaluating arithmetic expressions (e.g. a + b – c) :
postfix calculation
Infix to postfix conversion
Traversing a maze Will look at this later in the
course
22
1 Stack: Usage
s d
Stack s;
s.push (1);
s.push (2);
s.push (3); 3
d = s.peek ();
s.pop ();
s.push (4);
s.pop (); 3
4
2
1
23
2 Stack Implementation: Array
Use an Array with a top index pointer
StackArr
arr
0 1 2 3 4 5 6 7 8 9
push(“6”);
1 2 3 4 5 6 7 push(“7”);
pop();
10
maxsize
top
24
3 Stack Implementation: Linked List (1/6)
A class can be defined in 2 ways:
via inheritance we will not look into this
via composition, as shown below
class A {
public B b = new B (…); // A is composed of instance of B
…
}
25
3 Stack Implementation: Linked List (2/6)
(Composition): Use BasicLinkedList
list
Instance attribute
Top = Front of List
BasicLinkedList
head num_nodes
4
a1 a2 a3 a4
26
5 Application 1: Bracket Matching
Ensures that pairs of brackets are properly matched
An example: {a,(b+f[4])*3,d+f[5]}
Incorrect examples:
27
5 Application 1: Bracket Matching
create empty stack
for every char read Q: What type of error does
{ the last line test for?
if open bracket then
A: too many closing brackets
push onto stack B: too many opening brackets
if close bracket, then C: bracket mismatch
if doesn’t match or underflow then flag error
else pop from the stack [ ]
}
(
[ ) ]
if stack is not empty then flag error
Example { }
{ a -( b + f [ 4 ] ) * 3 * d + f [ 5 ] }
Stack
28
5 Applicn 2: Evaluating Arithmetic Expression
Terms
Expression: a=b+c*d
Operands: a, b, c, d
Operators: =, +, –, *, /, %
Precedence rules: Operators have priorities over
one another as indicated in a table (which can be
found in most books)
Example: * and / have higher precedence over + and –.
For operators at the same precedence (such as * and
/), we process them from left to right
29
5 Applicn 2: Evaluating Arithmetic Expression
2+3*4
2+(3*4) 2 3 4 * +
30
5 Applicn 2: Evaluating Arithmetic Expression
Algorithm: Evaluating Postfix expression with stack
Create an empty stack Infix postfix
for each item of the expression, 2 * (3 + 4) 2 3 4 + *
if it is an operand,
push it on the stack
if it is an operator, 2 s.push(2)
pop arguments from stack; 3 s.push(3)
perform the operation; 4 s.push(4)
push the result onto the stack + arg2 = s.pop ()
Stack arg1 = s.pop ()
s.push (arg1 + arg2)
* arg2 = s.pop ()
arg1 = s.pop ()
arg1
s.push (arg1 * arg2)
32
4
arg2
3 7
47
2 14
31
6-9 Queues
First-In-First-Out (FIFO)
6 Queue ADT: Operations
A Queue is a collection of data that is accessed
in a first-in-first-out (FIFO) manner
Major operations: “poll” (or “dequeue”), “offer” (or
“enqueue”), and “peek”.
poll()
offer(item)
Back of
Front of
queue
queue
queue
peek()
27
6 Queue ADT: Uses
Print queue
Simulations
Breadth-first traversal of graph look at this
later in the course
Checking palindromes - for illustration only as it
is not a real application of queue
34
6 Queue: Usage
Queue q;
q.offer (“a”);
q.offer (“b”); q
d a
q.offer (“c”);
d = q.peek ();
a b c e
q.poll ();
front
q.offer (“e”); back
q.poll ();
35
7 Queue Implementation: Array
Use an Array with front and back indices
arr
0 1 2 3 4 5 6 7 8 9
offer(“F”);
A B C D E F G offer(“G”);
poll();
10
maxsize
front back
36
7 Queue Implementation: Array (2/7)
“Circular” Array needed to recycle space
0 1 2 3 4 5 6 7 8 9
Given a queue A B C D E F G
front
back
9 0 front
8 1
back A
B To advance the indexes, use
front = (front+1) % maxsize;
C 2
7 back = (back+1) % maxsize;
G D
F E 3
6
5 4
37
7 Queue Implementation: Array (3/7)
Question: what does (front == back) mean?
A: Full queue
B: Empty queue C: Both A and B
C: Both A and B
D: Neither A nor B
38
7 Queue Implementation: Array (4/7)
Ambiguous full/empty state
Queue e f c d Queue
Empty F F Full
State B B State
39
8 Queue Implementn: Linked List
Use TailedLinkedList
Do not use BasicLinkedList as we would like to use
addBack() of TailedLinkedList.
QueueLL – class of LinkedList based implementation of Queue
list
TailedLinkedList
head num_nodes tail
4
a1 a2 a3 a4
40
10 Palindromes
42
Summary
We can simply use array or linkedlist to
achieve what we want without creating the
Stack and Queue ADT.
But their names immediately let us know
what they are suppose to achieve.
Most of the time, stack and queue help us to
improve our algorithms and their efficiency.
43