Chapter 3 Lists, Stacks, and Queues

Download Report

Transcript Chapter 3 Lists, Stacks, and Queues

Chapter 3
Lists, Stacks, and Queues
• Abstract Data Types (ADTs)
• Lists
• Stacks
• Queues
2110211 Intro. to Data Structures
1
Array
• An array is a data structure that holds multiple values
of the same type.
• The length of an array is established when the array is
created (at runtime). After creation, an array is a fixedlength structure.
Array Creation
int [] a;
a = new int[10];
int [] b = new int[10];
int [] c = a;
int [] d = {1, 2, 3, 4};
2110211 Intro. to Data Structures
2
Example 1 : Programming with array
public class MyData {
public static void main(String [] args) {
int [] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
print(data);
System.out.println( findMax(data) );
System.out.println( sum(data) );
}
public static void print(int [] d) {
for (int i = 0; i < d.length; i++ ) {
System.out.println( d[i] );
}
}
2110211 Intro. to Data Structures
3
public static int findMax(int [] d) {
int max;
for (max = d[0], int i = 1; i < d.length; i++) {
if (d[i] > max) max = d[i];
}
return max;
}
public static int findMin(int [] d) {
int min;
for (min = d[0], int i = 1; i < d.length; i++) {
if (d[i] > min) min = d[i];
}
return min;
}
2110211 Intro. to Data Structures
4
public static int sum(int [] d) {
int sum = 0;
for (int i = 0; i < d.length; i++)
sum += d[i];
return sum;
}
}
2110211 Intro. to Data Structures
5
Example 2 : Programming with a new data type (MyData)
public class MyProg {
public static void main(String [] args) {
MyData data = new Mydata();
for (int i = 0; i < 10; i++) {
data.add(i);
}
data.print();
System.out.println( data.findMax() );
System.out.println( data.sum() );
}
}
2110211 Intro. to Data Structures
6
public class MyData {
private int [] data;
private int size;
MyData() {
data = new int[100];
size = 0;
}
public void add( int x ) {
data[size] = x;
size++;
}
2110211 Intro. to Data Structures
7
public int findMax() {
int max;
for (max = data[0], int i = 1; i < size; i++)
if (data[i] > max) max = data[i];
return max;
}
public int findMin() {
int min = 0;
for (min =data[0], int i = 1; i < size; i++)
if (data[i] > min) min = data[i];
return min;
}
2110211 Intro. to Data Structures
8
public int sum() {
int sum = 0;
for (int i = 0; i < size; i++)
sum += data[i];
return sum;
}
public void print() {
for (int i = 0; i < size; i++ )
System.out.println( data[i] );
}
}
2110211 Intro. to Data Structures
9
Abstract Data Types (ADTs)
• Data values
• Operations to perform on the values
• Examples:
– MyData ( data = integer values, operations = add, print,
findMax, findMin, sum)
– Set (data = members, operations = union, intersect,
isMember)
– String (data = string of characters, operations = print,
append, find)
2110211 Intro. to Data Structures
10
Lists
• A set of data objects
• The data objects (elements) are arranged in
some order
• Data: A1, A2, A3, . . . , AN
• Operations: insert, remove, find, findKth
2110211 Intro. to Data Structures
11
Array Implementation of List
• Insert
insert(10,4)
10
34
12
52
16
12
34
12
52
10
16
2110211 Intro. to Data Structures
12
12
• Remove
remove(52)
34
12
52
10
16
12
• printList
printList() prints 34 12 10 16 12
2110211 Intro. to Data Structures
13
• findKth
34
12
10
16
12
findKth(2) returns 12
• find
find(16) returns 4
2110211 Intro. to Data Structures
14
Example 3 : Array Implementation of List
public class MyProg {
public static void main(String [] args) {
ListArray data = new ListArray();
for (int i = 1; i <= 10; i++) {
data.insert(i, i);
}
data.remove( data.findMax() );
data.printList();
}
}
2110211 Intro. to Data Structures
15
public class ListArray {
private int [] data;
private int size;
ListArray() {
data = new int[100];
size = 0;
}
public void insert(int x, int i) {
for (int n = size; n >= i; n--)
data[n+1] = data[n];
data[i] = x;
size++;
}
2110211 Intro. to Data Structures
16
public void remove(int x) {
int n;
for (n = find(x); n != -1 && n < size; n++)
data[n] = data[n+1];
size--;
}
public int find(int x) {
int i;
for (i = 1; i <= size; i++)
if (data[i] == x) break;
if (i > size) return -1; else return i;
}
2110211 Intro. to Data Structures
17
public int findKth(int k) {
return data[k];
}
public int findMax() {
int max = data[1];
for (int i = 2; i <= size; i++)
if (data[i] > max) max = data[i];
return max;
}
public void printList() {
for (int i = 1; i <= size; i++ )
System.out.println( data[i] );
}
}
2110211 Intro. to Data Structures
18
Array Implementation of List
• Size of the list must be known in order to
allocate an array with sufficient size
• All elements are adjacent in memory
• printList and find take linear time O(N)
• findKth takes constant time O(1)
2110211 Intro. to Data Structures
19
Array Implementation of List
• insert must push the tail of the list down
• remove must shift the tail of the list up
• insert and remove take linear time O(N)
• N successive inserts requires quadratic time O(N2)
• Expensive
2110211 Intro. to Data Structures
20
2110211 Intro. to Data Structures
21
Linked Lists
• A linked list consists of nodes
(not necessarily adjacent in memory)
• Each node contains
– data
– link (object reference) to the next node
2110211 Intro. to Data Structures
22
Linked Lists with header node
A1
A2
A3
header
empty list
header
2110211 Intro. to Data Structures
23
Three Classes in Linked List
LinkedList
LinkedListItr
header
current
A1
ListNode
ListNode
A2
ListNode
2110211 Intro. to Data Structures
A3
ListNode
24
Objects in Linked List
theList
theItr
LinkedList
current
header
ListNode
next
element
Object
LinkedListItr
ListNode
next
element
Object
ListNode
next
element
Object
2110211 Intro. to Data Structures
ListNode
next
element
Object
25
public class LinkedList
{
private ListNode header;
public LinkedList( ) { }
public boolean isEmpty( ) { }
public void makeEmpty( ) { }
public LinkedListItr zeroth( ) { }
public LinkedListItr first( ) { }
public LinkedListItr find( Object x ) { }
public void remove( Object x ) { }
public LinkedListItr findPrevious( Object x ) { }
public void insert( Object x, LinkedListItr p ) { }
}
2110211 Intro. to Data Structures
26
class ListNode
{
Object element;
ListNode next;
ListNode ( Object theElement )
{
this( theElement, null );
}
ListNode ( Object theElement, ListNode n )
{
element = theElement;
next = n;
}
}
2110211 Intro. to Data Structures
27
public class LinkedListItr
{
ListNode current;
LinkedListItr( ListNode theNode )
{ current = theNode; }
public boolean isPastEnd( )
{ return current == null; }
public Object retrieve( )
{ return isPastEnd( ) ? Null : current.element; }
public void advance( )
{ if (!isPastEnd( ) ) current = current.next; }
}
2110211 Intro. to Data Structures
28
public class MyProg {
public static void main( String [ ] args )
{
LinkedList theList = new LinkedList( );
LinkedListItr theItr= theList.zeroth( );
int i;
printList( theList );
for( i = 0; i < 10; i++ ) {
theList.insert( new MyInteger( i ), theItr );
printList( theList );
theItr.advance( );
}
}
2110211 Intro. to Data Structures
29
for( i = 0; i < 10; i += 2 ) theList.remove( new MyInteger( i ) );
for( i = 0; i < 10; i++ )
if( ( i % 2 == 0 ) != ( theList.find( new MyInteger( i ) ).isPastEnd( ) ) )
System.out.println( "Find fails!" );
printList( theList );
} // end main
} // end class MyProg
2110211 Intro. to Data Structures
30
Linked Lists
A1
A2
A3
insert
A1
A2
A3
x
remove
A1
A2
x
2110211 Intro. to Data Structures
A3
31
public class LinkedList
{
private ListNode header;
public LinkedList( )
{ header = new ListNode( null ); }
public boolean isEmpty( )
{ return header.next == null; }
public void makeEmpty( )
{ header.next = null; }
public LinkedListItr zeroth( )
{ return new LinkedListItr( header ); }
2110211 Intro. to Data Structures
32
public LinkedListItr first( )
{ return new LinkedListItr( header.next ); }
public void insert( Object x, LinkedListItr p )
{
if( p != null && p.current != null )
p.current.next = new ListNode( x, p.current.next );
}
public LinkedListItr find( Object x )
{
/* 1*/
ListNode itr = header.next;
/* 2*/
while( itr != null && !itr.element.equals( x ) )
/* 3*/
itr = itr.next;
/* 4*/
return new LinkedListItr( itr );
}
2110211 Intro. to Data Structures
33
public LinkedListItr findPrevious( Object x )
{
/* 1*/
ListNode itr = header;
/* 2*/
while( itr.next != null && !itr.next.element.equals( x ) )
/* 3*/
itr = itr.next;
/* 4*/
return new LinkedListItr( itr );
}
public void remove ( Object x )
{
LinkedListItr p = findPrevious( x );
if( p.current.next != null )
p.current.next = p.current.next.next; // Bypass deleted node
}
2110211 Intro. to Data Structures
34
public static void printList( LinkedList theList )
{
if( theList.isEmpty( ) )
System.out.print( "Empty list" );
else
{
LinkedListItr itr = theList.first( );
for( ; !itr.isPastEnd( ); itr.advance( ) )
System.out.print( itr.retrieve( ) + " " );
}
System.out.println( );
}
2110211 Intro. to Data Structures
35
public static void main( String [ ] args )
{
LinkedList theList = new LinkedList( );
LinkedListItr theItr= theList.zeroth( );
int i;
printList( theList );
for( i = 0; i < 10; i++ ) {
theList.insert( new MyInteger( i ), theItr );
printList( theList );
theItr.advance( );
}
2110211 Intro. to Data Structures
36
for( i = 0; i < 10; i += 2 ) theList.remove( new MyInteger( i ) );
for( i = 0; i < 10; i++ )
if( ( i % 2 == 0 ) != ( theList.find( new MyInteger( i ) ).isPastEnd( ) ) )
System.out.println( "Find fails!" );
printList( theList );
} // end main
} // end class LinkedList
2110211 Intro. to Data Structures
37
Linked List
• Size of the list is not known when the list is
created
• All elements need not be adjacent in memory
• Often require less memory space than array
• printList, find and findPrevious take linear time
O(N)
• insert and remove take constant time O(1)
2110211 Intro. to Data Structures
38
Circular linked list
A1
A2
A3
Doubly linked list
A1
A2
A3
Double circular linked list
A1
A2
2110211 Intro. to Data Structures
A3
39
Example: Polynomial
• aNxN + aN-1xN-1 + aN-2xN-2 + . . . + a1x1 + a0
• P1(x) = 10x1000 + 5x14 + 1
• P2(x) = 3x1990 - 2x1492 +11x + 5
• Can be implemented by using array or linked
list
2110211 Intro. to Data Structures
40
Array Implementation of Polynomial
• Array of coefficients
x0
x1
x2
x3
x4
120
5
0
1
15
P1(x) = 15x4 + x3 + 5x + 120
2110211 Intro. to Data Structures
41
Array Implementation of Polynomial
public class Polynomial
{
public Polynomial( ) { }
public void insertTerm( int coef, int exp ) { }
public void zeroPolnomial( ) { }
public Polynomial add( Polynomial rhs ) { }
public Polynomial multiply( Polynomial rhs ) { }
public void print( ) { }
public static final int MAX_DEGREE = 100;
private int coeffArray[ ] = new int [MAX_DEGREE + 1];
private int highPower = 0;
}
2110211 Intro. to Data Structures
42
public Polynomial add( Polynomial rhs )
{
Polynomial sum = new Polynomial( );
sum.highPower = max( highPower, rhs.highPower );
for( int i = sum.highPower; i>= 0; i-- )
sum.coeffArray[ i ] = coeffArray[ i ] +
rhs.coeffarray[ i ];
return sum;
}
2110211 Intro. to Data Structures
43
Linked List Implementation of Polynomial
10 1000
P1
14
1
0
P1(x) = 10x1000 + 5x14 + 1
3 1990
P2
5
-2 1492
11
1
5
0
P2(x) = 3x1990 - 2x1492 +11x + 5
2110211 Intro. to Data Structures
44
Linked List Implementation of Polynomial
public class Literal
{ int coefficient;
int exponent;
}
public class Polynomial
{
private LinkedList terms;
public Polynomial( ) { }
public void insertTerm( int coef, int exp ) { }
public void zeroPolnomial( ) { }
public Polynomial add( Polynomial rhs ) { }
public Polynomial multiply( Polynomial rhs ) { }
public void print( ) { }
}
2110211 Intro. to Data Structures
45
Bucket Sort
• Sort N integers in the range 1 to M
• Use M buckets, one bucket for each integer i
• Bucket i stores how many times i appears in the
input. Initially, all buckets are empty.
• Read input and increase values in buckets
• Finally, scan the buckets and print the sorted list
2110211 Intro. to Data Structures
46
Bucket Sort
3, 1, 3, 5, 8, 7, 4, 2, 9, 5, 4, 10, 4
1
1
2
3
2
0
1
1
1
1
1, 2, 3, 3, 4, 4, 4, 5, 5, 7, 8, 9, 10
2110211 Intro. to Data Structures
47
Radix Sort
• Bucket sort needs M = max - min + 1 buckets
• If M >> N, lots of buckets are not used
• Radix sort needs less buckets than bucket sort
• Performs several passes of bucket sort;
one pass for each digit
• Sort by the least significant digit first
2110211 Intro. to Data Structures
48
0
1 512 343
8
729
1 216 27
0 512 125
64
27
8
1
0 125 216 343
64 125 216
343
27
8 729
64
512
2110211 Intro. to Data Structures
729
49
Radix Sort
• More than one (possibly different) number
could fall into the same bucket
• When several numbers enter a bucket, they
enter in sorted order
• Numbers in each bucket is kept in a list
• Use 10 lists
2110211 Intro. to Data Structures
50
Multilists
Problem:
• A university with 40,000 students and 2,500
courses
• First report lists, for each class, the registered
students
• Second report lists, for each student, the classes
that the student is registered
2110211 Intro. to Data Structures
51
Multilists
S1
S2
S3
S4
C1
C2
C3
C4
2110211 Intro. to Data Structures
52
Cursor Implementation of Linked Lists
• Instead of calling new each time a node is
needed, lots of nodes are created at the
beginning
• Getting a node from the collection ( alloc ) and
returning a node to the collection ( free ) are
implemented by the programmer
2110211 Intro. to Data Structures
53
Cursor Implementation of Linked Lists
freeList
Allocation
freeList L1
freeList L1
2110211 Intro. to Data Structures
54
Cursor Implementation of Linked Lists
Two Lists
freeList L1
L2
Deallocation (free)
freeList L1
L2
2110211 Intro. to Data Structures
55
public class CursorList
{
private static int alloc( ) { }
private static void free( ) { }
public CursorList( )
{ header = alloc( ); cursorSpace[ header ].next = 0; }
private int header;
static CursorNode[ ] cursorSpace;
private static final int SPACE_SIZE = 100;
static
{
cursorSpace = new CursorNode[ SPACE_SIZE ];
for( int i = 0; i < SPACE_SIZE; iI++ )
cursorSpace[ i ] = new CursorNode( null, i+1 );
cursorSpace[ SPACE_SIZE - 1 ] .next = 0;
}
}
2110211 Intro. to Data Structures
56
private static int alloc( )
{
int p = cursorSpace[ 0 ].next;
cursorSpace[ 0 ].next = cursorSpace[ p ].next;
if ( p == 0 ) throw new OutOfMemoryError( );
return p;
}
private static void free( int p )
{
cursorSpace[ p ].element = null;
cursorSpace[ p ].next = cursorSpace[ 0 ].next;
cursorSpace[ 0 ].next = p;
}
2110211 Intro. to Data Structures
57
2110211 Intro. to Data Structures
58
Stack
4
3
2
1
PUSH 5
POP
5
5
4
3
2
1
5
4
3
2
1
2110211 Intro. to Data Structures
4
3
2
1
59
Stack
• A special kind of list
• Only the element at the end of the list (called
the top of stack) can be operated on
• Only three operations
– PUSH : put one element on the top of the stack
– POP
: take one element from the top of the stack
– TOP
: see the value of the element on the top
• Last In, First Out (LIFO)
2110211 Intro. to Data Structures
60
Balancing Symbols
• Check whether pairs of symbols are balanced
• Balanced: ( ), [ ], { }, ( ( ) ), { ( [ ] ) }
• Unbalanced: ( (, ( [ ) ], [ ] )
2110211 Intro. to Data Structures
61
Balancing Symbols: Algorithm
• Read characters until end of file
• For an opening symbol, push it onto the stack
• For an closing symbol, pop the stack
• Report an error if:
– Stack empty when trying to pop
– Popped symbol is not the corresponding opening symbol
– Stack is not empty when end of file is reached
2110211 Intro. to Data Structures
62
Balancing Symbols
[])
([)]
((( ))
2110211 Intro. to Data Structures
63
Postfix Expressions
• Normal : 1 + 2 * 3 + 4 * 5
( ( (1 + 2) * 3 ) + 4 ) * 5 = 65
• With Parentheses: 1 + ( 2 * 3 ) + ( 4 * 5 )
( 1 + ( 2 * 3 ) ) + ( 4 * 5 ) = 27
• Postfix Expression: 1 2 3 * 4 5 * + +
( 1 ( ( 2 3 * ) ( 4 5 * ) + ) + ) = 27
2110211 Intro. to Data Structures
64
Evaluation of Postfix Expressions
• When a number is seen, it is pushed onto the stack
• When an operator is seen, the operator is applied
to the two numbers that are popped from the stack.
The result is pushed onto the stack
2110211 Intro. to Data Structures
65
Postfix Expressions
Example: 1 2 3 * 4 5 * + +
*45*++
3
2
1
45*++
*++
++
+
6
1
5
4
6
1
20
6
1
26
1
2110211 Intro. to Data Structures
66
Infix to Postfix Conversion
• Infix:
a+b*c+(d*e+f)*g
• Postfix: a b c * + d e * f + g * +
2110211 Intro. to Data Structures
67
Infix to Postfix Conversion
• When an operand is seen, print it.
• When an operator is seen, pop the stack and print.
until a lower-priority operator or ( is found.
Then, push the operator onto the stack.
• When a ( is seen, push it onto the stack.
• When a ) is seen, pop the stack and print until a (
is popped. ( and ) are not printed.
• When input is empty, pop the stack and print until
it is empty
2110211 Intro. to Data Structures
68
Infix to Postfix Conversion
Input
Action
operand
Print it
operator
Pop and print until a lower precedence operator or a
( is found. Push the operator.
(
Push
)
Pop and print until a ( is found. Pop (.
are not printed
empty
( and )
pop and print all
2110211 Intro. to Data Structures
69
Infix to Postfix Conversion
Input
a+b*c+(d*e+f)*g
Output
abc*+de*f+g*+
2110211 Intro. to Data Structures
70
Method Calls
a()
{
...
b( );
...
}
b( )
{
...
c( );
...
}
2110211 Intro. to Data Structures
c( )
{
...
}
71
Method Calls
a:
b:
.
.
call b
.
.
return
c:
.
.
call c
.
.
return
2110211 Intro. to Data Structures
.
.
.
return
72
a:
10: . . .
11: call
b
12: . . .
Method
Calls
and
Stack
c:
b:
101: . . .
102: call
c
223: . . .
224:
return
103: . . .
1
2
b:
102: call c
103: . . .
104: return
103
1
2
2110211 Intro. to Data Structures
a:
10: . . .
11: call
b
12: . . .
1
2
73
Method Calls
• When a call is made to a new method, the
calling routine must save
– current location ( return address )
– register values
– local variables
• call and return are balancing symbols
2110211 Intro. to Data Structures
74
Activation Record (Stack Frame)
return address
previous frame
arguments
local variables
return address
previous frame
arguments
local variables
return address
previous frame
arguments
local variables
2110211 Intro. to Data Structures
75
Exception Handling in Java (page 16)
• Exception is a mechanism to catch errors and
take action on the errors.
• An exception is thrown when an error condition
occurs.
• An exception is propagated back through the
calling sequence until some routing catches it.
2110211 Intro. to Data Structures
76
try
// code that might cause an exception
{ statements }
catch (exception_type identifier)
// exception handler for an exception type
{ statements }
catch (exception_type identifier)
// exception handler for another exception
type
{ statements }
2110211 Intro. to Data Structures
77
Underflow and Overflow Exceptions
• Underflow exception signals an illegal
attempt to extract from an empty collection
• Overflow exception signal that a capacity has
been exceeded.
public void pop( ) throws Underflow
{
if( isEmpty( ) ) throw new Underflow( );
topOfStack = topOfStack.next;
}
2110211 Intro. to Data Structures
78
Linked List Implementation of Stacks
public class StackLi
{
private ListNode topOfStack;
public
public boolean
public boolean
public void
StackLi( )
{ topOfStack = null; }
isfull( )
{ return false; }
isEmpty( )
{ return topOfStack == null; }
makeEmpty( ) { topOfStack = null; }
public void
public Object
public Object
public void
push( Object x ) { }
topAndPop( ) { }
top( ) { }
pop( ) { }
}
2110211 Intro. to Data Structures
79
Linked List Implementation of Stacks
public static void main( String [ ] args )
{
StackLi s = new StackLi( );
for( int i = 0; i < 10; i++ )
s.push( new MyInteger( i ) );
while( !s.isEmpty( ) )
System.out.println( s.topAndPop( ) );
}
2110211 Intro. to Data Structures
80
Linked List Implementation of Stacks
public void push( Object x )
{
topOfStack = new ListNode( x, topOfStack );
}
public Object topAndPop( )
{
if( isEmpty( ) ) return null;
Object topItem = topOfStack.element;
topOfStack = topOfStack.next;
return topItem;
}
2110211 Intro. to Data Structures
81
Linked List Implementation of Stacks
public Object top( )
{
if( isEmpty( ) ) return null;
return topOfStack.element;
}
public void pop( ) throws Underflow
{
if( isEmpty( ) ) throw new Underflow( );
topOfStack = topOfStack.next;
}
2110211 Intro. to Data Structures
82
Array Implementation of Stacks
public class StackAr
{
private Object [ ] theArray;
private int
topOfStack;
static final int
DEFAULT_CAPACITY = 10;
public StackAr( ) { this( DEFAULT_CAPACITY ); }
public StackAr( int capacity ) {
theArray = new Object[ capacity ];
topOfStack = -1;
}
2110211 Intro. to Data Structures
83
Array Implementation of Stacks
public boolean isEmpty( ) { return topOfStack == -1; }
public boolean isFull( ) { return topOfStack == theArray.length - 1; }
public void
makeEmpty( ) { topOfStack = -1; }
public void
push( Object x ) { }
public Object topAndPop( ) { }
public Object top( ) { }
public void
pop( ) { }
}
2110211 Intro. to Data Structures
84
Array Implementation of Stacks
public static void main( String [ ] args )
{
StackAr s = new StackAr( 12 );
try
{
for( int i = 0; i < 10; i++ )
s.push( new MyInteger( i ) );
}
catch( Overflow e ) { System.out.println( "Unexpected overflow" ); }
while( !s.isEmpty( ) )
System.out.println( s.topAndPop( ) );
}
2110211 Intro. to Data Structures
85
Array Implementation of Stacks
public void push( Object x ) throws Overflow
{
if( isFull( ) ) throw new Overflow( );
theArray[ ++topOfStack ] = x;
}
public Object topAndPop( )
{
if( isEmpty( ) ) return null;
Object topItem = top( );
theArray[ topOfStack-- ] = null;
return topItem;
}
2110211 Intro. to Data Structures
86
Array Implementation of Stacks
public void pop( ) throws Underflow
{
if( isEmpty( ) ) throw new Underflow( );
theArray[ topOfStack-- ] = null;
}
public Object top( )
{
if( isEmpty( ) ) return null;
return theArray[ topOfStack ];
}
2110211 Intro. to Data Structures
87
Queue
• Queue is a special kind of list
• Two operations
– Enqueue: insert an element at the end
– Dequeue: delete an element at the front
• O(1) running times for both operations
• First-Come First-Served
2110211 Intro. to Data Structures
88
Application of Queues
• A queue of requests waiting for a service
• Examples
– Event Simulation: queues at phone booth, bank
– Job scheduling: print jobs submitted to a printer
– Buffering: keyboard buffer
2110211 Intro. to Data Structures
89
Array Implementation of Queues
1
2
front
enqueue
1
3
back
2
3
front
dequeue
4
back
2
front
3
4
back
2110211 Intro. to Data Structures
90
Circular Array
7
8
9
front
enqueue
11
back
7
10
back
8
9
10
front
2110211 Intro. to Data Structures
91
Empty Queue
2 entries
dequeue 10
1 entry left
11
10
back
front
11
front back
dequeue 11
0 entry left
back
front
2110211 Intro. to Data Structures
92
Array Implementation of Queues
public class QueueAr
{
private Object [ ] theArray;
private int
currentSize;
private int
front;
private int
back;
static final int
DEFAULT_CAPACITY = 10;
public QueueAr( )
public QueueAr( int capacity )
public boolean isEmpty( )
public boolean isFull( )
{ this( DEFAULT_CAPACITY); }
{}
{ return currentSize == 0 }
{ return currentSize == theArray.length; }
2110211 Intro. to Data Structures
93
Array Implementation of Queues
public void
public Object
public void
public int
public Object
makeEmpty( ) { }
getFront( ) { }
enqueue( Object x ) throws Overflow { }
increment( int x) { }
dequeue( ) { }
}
2110211 Intro. to Data Structures
94
public static void main( String [ ] args )
{
QueueAr q = new QueueAr( );
try
{
for( int i = 0; i < 10; i++ )
q.enqueue( new MyInteger( i ) );
}
catch( Overflow e ) { System.out.println( "Unexpected overflow" ); }
while( !q.isEmpty( ) )
System.out.println( q.dequeue( ) );
}
2110211 Intro. to Data Structures
95
public QueueAr( int capacity )
{
theArray = new Object[ capacity ];
makeEmpty( );
}
public void makeEmpty( )
{
currentSize = 0;
front = 0;
back = -1;
}
2110211 Intro. to Data Structures
96
public void enqueue( Object x ) throws Overflow
{
if ( isFull( ) ) throw new Overflow( );
back = increment( back );
theArray[ back ] = x;
currentSize++;
}
private int increment( int x )
{
if ( ++x == theArray.length ) x = 0;
return x;
}
2110211 Intro. to Data Structures
97
public Object dequeue( )
{ if ( isEmpty( ) ) return null;
currentSize--;
Object frontItem = theArray[ front ];
theArray[ front ] = null;
front = increment( front );
return frontItem;
}
public Object getFront( )
{
if( isEmpty( ) ) return null;
return theArray[ front ];
}
2110211 Intro. to Data Structures
98
Linked List Implementation of Queues
Exercise.
2110211 Intro. to Data Structures
99