Chapter 3 Lists, Stacks, and Queues - PowerPoint PPT Presentation

About This Presentation
Title:

Chapter 3 Lists, Stacks, and Queues

Description:

public LinkedListItr zeroth( ) { } public LinkedListItr first ... LinkedListItr theItr= theList.zeroth( ); int i; printList( theList ); for( i = 0; i 10; i ) ... – PowerPoint PPT presentation

Number of Views:425
Avg rating:3.0/5.0
Slides: 100
Provided by: veeramu
Category:

less

Transcript and Presenter's Notes

Title: Chapter 3 Lists, Stacks, and Queues


1
Chapter 3Lists, Stacks, and Queues
  • Abstract Data Types (ADTs)
  • Lists
  • Stacks
  • Queues

2
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 fixed-length structure.
  • Array Creation
  • int a
  • a new int10
  • int b new int10
  • int c a
  • int d 1, 2, 3, 4

3
  • 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 lt d.length i )
  • System.out.println( di )

4
  • public static int findMax(int d)
  • int max
  • for (max d0, int i 1 i lt d.length
    i)
  • if (di gt max) max di
  • return max
  • public static int findMin(int d)
  • int min
  • for (min d0, int i 1 i lt d.length
    i)
  • if (di gt min) min di
  • return min

5
  • public static int sum(int d)
  • int sum 0
  • for (int i 0 i lt d.length i)
  • sum di
  • return sum

6
  • 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 lt 10 i)
  • data.add(i)
  • data.print()
  • System.out.println( data.findMax() )
  • System.out.println( data.sum() )

7
  • public class MyData
  • private int data
  • private int size
  • MyData()
  • data new int100
  • size 0
  • public void add( int x )
  • datasize x
  • size

8
  • public int findMax()
  • int max
  • for (max data0, int i 1 i lt size i)
  • if (datai gt max) max datai
  • return max
  • public int findMin()
  • int min 0
  • for (min data0, int i 1 i lt size i)
  • if (datai gt min) min datai
  • return min

9
  • public int sum()
  • int sum 0
  • for (int i 0 i lt size i)
  • sum datai
  • return sum
  • public void print()
  • for (int i 0 i lt size i )
  • System.out.println( datai )

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

11
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

12
Array Implementation of List
  • Insert
  • insert(10,4)

13
  • Remove
  • remove(52)
  • printList

printList() prints 34 12 10 16 12
14
  • findKth

findKth(2) returns 12
  • find

find(16) returns 4
15
  • Example 3 Array Implementation of List
  • public class MyProg
  • public static void main(String args)
  • ListArray data new ListArray()
  • for (int i 1 i lt 10 i)
  • data.insert(i, i)
  • data.remove( data.findMax() )
  • data.printList()

16
  • public class ListArray
  • private int data
  • private int size
  • ListArray()
  • data new int100
  • size 0
  • public void insert(int x, int i)
  • for (int n size n gt i n--)
  • datan1 datan
  • datai x
  • size

17
  • public void remove(int x)
  • int n
  • for (n find(x) n ! -1 n lt size n)
  • datan datan1
  • size--
  • public int find(int x)
  • int i
  • for (i 1 i lt size i)
  • if (datai x) break
  • if (i gt size) return -1 else return i

18
  • public int findKth(int k)
  • return datak
  • public int findMax()
  • int max data1
  • for (int i 2 i lt size i)
  • if (datai gt max) max datai
  • return max
  • public void printList()
  • for (int i 1 i lt size i )
  • System.out.println( datai )

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

20
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

21
(No Transcript)
22
Linked Lists
  • A linked list consists of nodes
    (not necessarily adjacent in memory)
  • Each node contains
  • data
  • link (object reference) to the next node

23
Linked Lists with header node
empty list
24
Three Classes in Linked List
LinkedList
LinkedListItr
header
current
ListNode
ListNode
ListNode
ListNode
25
Objects in Linked List
theList
theItr
26
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 )
27
class ListNode Object element ListNode
next ListNode ( Object theElement )
this( theElement, null )
ListNode ( Object theElement, ListNode n )
element theElement next
n
28
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
29
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 lt 10 i )
theList.insert( new MyInteger( i ), theItr
) printList( theList )
theItr.advance( )
30
for( i 0 i lt 10 i 2 ) theList.remove(
new MyInteger( i ) ) for( i 0 i lt 10 i
) if( ( i 2 0 ) ! (
theList.find( new MyInteger( i ) ).isPastEnd( ) )
) System.out.println( "Find
fails!" ) printList( theList )
// end main // end class MyProg
31
Linked Lists
insert
remove
32
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 )
33
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 )
34
public LinkedListItr findPrevious( Object x )
/ 1/ ListNode itr header / 2/
while( itr.next ! null !itr.next.element.equal
s( 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
35
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( )
36
public static void main( String args )
LinkedList theList new LinkedList(
) LinkedListItr theItr
theList.zeroth( ) int i
printList( theList ) for( i 0 i lt
10 i )
theList.insert( new MyInteger( i ), theItr )
printList( theList )
theItr.advance( )
37
for( i 0 i lt 10 i 2 ) theList.remove(
new MyInteger( i ) ) for( i 0 i lt 10 i
) if( ( i 2 0 ) ! (
theList.find( new MyInteger( i ) ).isPastEnd( ) )
) System.out.println( "Find
fails!" ) printList( theList )
// end main // end class LinkedList
38
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)

39
Circular linked list
Doubly linked list
Double circular linked list
40
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

41
Array Implementation of Polynomial
  • Array of coefficients

x0
x1
x2
x3
x4
P1(x) 15x4 x3 5x 120
42
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
43
public Polynomial add( Polynomial rhs
) Polynomial sum new Polynomial(
) sum.highPower max( highPower, rhs.highPower
) for( int i sum.highPower igt 0 i--
) sum.coeffArray i coeffArray i

rhs.coeffarray i return sum
44
Linked List Implementation of Polynomial
P1(x) 10x1000 5x14 1
P2(x) 3x1990 - 2x1492 11x 5
45
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( )
46
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

47
Bucket Sort
3, 1, 3, 5, 8, 7, 4, 2, 9, 5, 4, 10, 4
1
1
1
2
3
2
0
1
1
1
1, 2, 3, 3, 4, 4, 4, 5, 5, 7, 8, 9, 10
48
Radix Sort
  • Bucket sort needs M max - min 1 buckets
  • If M gtgt 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

49
2
50
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

51
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

52
Multilists
53
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

54
Cursor Implementation of Linked Lists
Allocation
55
Cursor Implementation of Linked Lists
Two Lists
Deallocation (free)
56
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 privat
e static final int SPACE_SIZE
100 static cursorSpace new CursorNode
SPACE_SIZE for( int i 0 i lt SPACE_SIZE
iI ) cursorSpace i new CursorNode(
null, i1 ) cursorSpace SPACE_SIZE - 1
.next 0
57
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
58
(No Transcript)
59
Stack
POP
5
5
60
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)

61
Balancing Symbols
  • Check whether pairs of symbols are balanced
  • Balanced ( ), , , ( ( ) ), (
    )
  • Unbalanced ( (, ( ) , )

62
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

63
Balancing Symbols
( )
)
( ( ( ) )
64
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

65
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

66
Postfix Expressions
Example 1 2 3 4 5
4 5
4 5



67
Infix to Postfix Conversion
  • Infix a b c ( d e f ) g
  • Postfix a b c d e f g

68
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

69
Infix to Postfix Conversion
70
Infix to Postfix Conversion
Input a b c ( d e f ) g Output a b
c d e f g
71
Method Calls
a ( ) . . . b( ) . . .
b( ) . . . c( ) . . .
c( ) . . .
72
Method Calls
a . . call b . .
return
b . . call c . .
return
c . . . return
73
Method Calls and Stack
a 10 . . . 11 call b 12 . . .
b 101 . . . 102 call c 103 . . .
c 223 . . . 224 return
b 102 call c 103 . . . 104 return
a 10 . . . 11 call b 12 . . .
74
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

75
Activation Record (Stack Frame)
76
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.

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

78
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

79
Linked List Implementation of Stacks
public class StackLi private
ListNode topOfStack public
StackLi( ) topOfStack null
public boolean isfull( )
return false public boolean isEmpty(
) return topOfStack null
public void makeEmpty( ) topOfStack
null public void push( Object
x ) public Object topAndPop( )
public Object top( )
public void pop( )
80
Linked List Implementation of Stacks
public static void main( String args )
StackLi s new StackLi( )
for( int i 0 i lt 10 i )
s.push( new MyInteger( i ) )
while( !s.isEmpty( ) )
System.out.println( s.topAndPop( ) )

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

83
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
84
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( )

85
Array Implementation of Stacks
public static void main( String args )
StackAr s new StackAr( 12 )
try for(
int i 0 i lt 10 i )
s.push( new MyInteger( i ) )
catch( Overflow e ) System.out.println(
"Unexpected overflow" ) while(
!s.isEmpty( ) )
System.out.println( s.topAndPop( ) )

86
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
87
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
88
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

89
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

90
Array Implementation of Queues
enqueue
dequeue
91
Circular Array
enqueue
92
Empty Queue
2 entries
dequeue 10 1 entry left
dequeue 11 0 entry left
93
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( )
this( DEFAULT_CAPACITY)
public QueueAr( int capacity ) public
boolean isEmpty( ) return currentSize
0 public boolean isFull( )
return currentSize theArray.length
94
Array Implementation of Queues
public void makeEmpty( )
public Object getFront( ) public void
enqueue( Object x ) throws Overflow
public int increment( int x)
public Object dequeue( )
95
public static void main( String args )
QueueAr q new QueueAr( )
try for( int i 0
i lt 10 i ) q.enqueue( new
MyInteger( i ) )
catch( Overflow e ) System.out.println(
"Unexpected overflow" ) while(
!q.isEmpty( ) )
System.out.println( q.dequeue( ) )
96
public QueueAr( int capacity ) theArray
new Object capacity makeEmpty(
) public void makeEmpty( ) currentSize
0 front 0 back -1
97
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
98
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
99
Linked List Implementation of Queues
Exercise.
Write a Comment
User Comments (0)
About PowerShow.com