Title: Queue and Stack
1Queue and Stack
- Abstract
- Queue
- Container where elements are added to one end and
removed from the other. - Stack
- Container where items are added and removed from
one end
2Queue and Stack
- Queue First In First Out (FIFO)
Out
In
Stack Last in First Out (LIFO)
In
Out
3Queue and StackPublic Methods
- Queue
- Add
- Remove
- isEmpty
- isFull
- Stack
- Push
- Pop
- isEmpty
- isFull
4Queue and StackImplementation
- Stack
- private Object items
- private int top
- Queue
- private Object items
- private int front, rear, count
5Queue Implementation
- Make the array circular
- Variables front, rear, count
front points to where the first element is
rear points to where next element goes
6itemsrear obj rear (rear 1)
items.length count
obj itemsfront front (front 1)
items.length count --
7public class Queue private Object items
private int front, rear, count public
Queue( int size ) items new
Objectsize front rear count 0
public boolean isEmpty() return
count 0 public boolean isFull ()
return count gt items.length
... // class Queue
8public class Queue private Object items
private int front, rear, count ...
public void add ( Object x )
itemsrear x rear (rear 1)
items.length count public
Object remove() Object x
itemsfront front (front 1)
items.length count -- return x
// class Queue
9Queue Class
front
0
rear
1
4
3
2
10Queue Class
Add B
front
front
0
0
A
A
1
4
B
1
4
3
rear
2
3
2
rear
11Queue Class
Add E
front
front
0
rear
0
A
A
1
4
E
B
1
4
B
C
D
D
C
3
2
3
rear
2
12Queue Class
Remove twice
0
rear
0
rear
1
4
x0
1
4
x2
front
front
3
2
3
2
13Method numItems
- As Implementer
- public int numItems()
-
- return count
-
14Method numItems
- As User
- public int numItems(Queue q, int qSize)
- (
- Queue tq new Queue(qSize)
- int num 0
- while ( !q.isEmpty() )
-
- tq.add( q.remove() )
- num
-
- while ( !tq.isEmpty() )
- q.add( tq.remove() )
- return num
-
- Is the 2nd while loop necessary?
15Method numItems
- As User
- public int numItems(Queue q, int qSize)
- (
- Queue tq new Queue(qSize)
- int num 0
- while ( !q.isEmpty() )
-
- tq.add( q.remove() )
- num
-
- q tq
- return num
-
- Pass by Value!
16Method numItems
- As User
- public int numItems(Queue q, int qSize)
- (
- Queue tq new Queue(qSize)
- int num 0
- while ( !q.isEmpty() )
-
- tq.add( q.remove() )
- num
-
- while ( !tq.isEmpty() )
- q.add( tq.remove() )
- return num
-
- The 2nd while loop is necessary!
- Can you do it without tq?
17Method numItems
- As User
- public int numItems(Queue q, int qSize)
- (
- Object tq new ObjectqSize
- int num 0
- while ( !q.isEmpty() )
-
- tqnum q.remove()
-
- for (int index 0 index lt num index )
- q.add( tqindex )
- return num
-
18Schedule
- Prog3 Grace time
- 9 pm, Thursday
- Prog4 Due Time
- 11 pm, Oct 28
- 1ReadOnly folder
- StackMain.txt
- TvectorMain.txt
- Friday
- No class!