updated 30 apr linked list and arraylist java311
TRANSCRIPT
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
1/52
Data Structures
Chapter 12
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
2/52
Chapter ContentsChapter Objectives12.1 Introductory Example: Countin Internet !ddresses12.2 "he ArrayList and LinkedList Classes
12.# Example: ! Stack !pplication and Class12.$ Example: ! Queue Class12.% !n Introduction to "rees&art o' the &icture: Data Structures
12.( )raphical*Internet +ava: ! PolygonSketcher Class
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
3/52
Chapter Objectives
Study the +ava collection classes, ArrayList and LinkedList
Sho- ho- to build collection classesStudy the stac and /ueue structures0earn about lin ed structures
lin ed lists and binary treesImplement and use lin ed structuresDiscover ho- collection classes are used
in raphical pro rammin
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
4/52
evie- !rrays
!n array stores a se/uence o' valuestype [] anArray = new type [ capacity ];
Dra-bac : – capacity o' array 'ixed – must no- max number o' values at compile
time – either the pro ram runs out o' space or-astes spaceSolution: collection classes –
capacity can ro- and shrin as pro ram runs
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
5/52
12.2 "he ArrayList andLinkedList ClassesCollection classes provide capability to
ro- and shrin as needed
Cate ories o' collection classes – 0ists: store collection o' items, some o'-hich may be the same
– Sets: store collection o' items -ith noduplicates
– aps: store collections o' pairs, eachassociates a .ey -ith an object
3ote List methods, table 12.1
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
6/52
ArrayList ClassImplements the 0ist usin an array – by usin an Object array, can store any
re'erence type –
cannot directly store primitive types – can indirectly store such values by usininstances o' their -rapper types
Consider the declaration: ArrayList addressSe uence = newArrayList!"; AddressSe eunce
si#e array
0
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
7/52
The List Interface and ArrayListClass (continued)The List Interface and ArrayListClass (continued)
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
8/52
The ArrayList ClassThe ArrayList Class
Simplest class that implements the 0ist inter'aceImprovement over an array object4sed -hen a pro rammer -ants to add ne- elements tothe end o' a list but still needs the capability to access
the elements stored in the list in arbitrary order
Simplest class that implements the 0ist inter'aceImprovement over an array object4sed -hen a pro rammer -ants to add ne- elements tothe end o' a list but still needs the capability to access
the elements stored in the list in arbitrary order
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
9/52
Performance of KWArrayList andthe Vector ClassPerformance of KWArrayList andthe Vector Class
Set and et methods execute in constant timeInsertin or removin elements is linear timeInitial release o' +ava !&I contained the 5ector class-hich has similar 'unctionality to the !rray0ist
6oth contain the same methods3e- applications should use !rray0ist rather than5ectorStac is a subclass o' 5ector
Set and et methods execute in constant timeInsertin or removin elements is linear timeInitial release o' +ava !&I contained the 5ector class-hich has similar 'unctionality to the !rray0ist
6oth contain the same methods3e- applications should use !rray0ist rather than5ectorStac is a subclass o' 5ector
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
10/52
!ddin to addressSe uence
"he commandaddressSe uence$add!anAddress%ounter"; – appends an!ddressCounter object to the
se/uence"he system -ill then 7
AddressSe eunce si#e array
0
[0] [1] [2] . . . [m-1]
128.159.4.201
Allocate the arrayMake first element
point to the Address%ounter
1
Up ate si!eattri"#te of the
ArrayList
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
11/52
4pdatin addressSe uence
Consider the command!!Address%ounter"addressSe uence$get!inde&""$incre'ent%ount!";(( assu'e inde& == )
AddressSe eunce si#e array
2
[0] [1] [2] . . . [m-1]
128.159.4.2011$ 1 12%.111.222.%%%$ 1
&ets this o"'ect(ast it as an Address%ounter
o"'ect
12%.111.222.%%%$2
)ncrement the countattri"#te
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
12/52
12%.111.%45.444$ 1
Enlar in the AddressSe uence !rray
8hen allocated array is 'ull, addinanother element 'orces replacin array-ith lar er one – ne- array o' n 9 m allocated – values 'rom old array copied into ne- array – old array replaced by ne- one
AddressSe eunce si#e array
2
[0] [1] [2] . . . [ n -1]
128.159.4.2011$ 1 12%.111.222.%%%$ 1
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
13/52
ArrayList Dra-bac
&roblems arise 'rom usin an array – values can be added only at bac o' ArrayList
– to insert a value and shi't others a'ter itre/uires extensive copyin o' values
– similarly, deletin a value re/uires shi'tin
8e need a sli htly di''erent structure toallo- simple insertions and deletions – the LinkedList class -ill accomplish this
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
14/52
"he LinkedList Class
)ivenLinkedList alist = new LinkedList!";$ $ $aList$add!new!integer!**"";aList$add!new!integer!++"";aList$add!new!integer!,,"";
esultin objectsho-n at le't
esultin objectsho-n at le't
aList
head si#e tail
%
**88 ++
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
15/52
0in ed 0ist Containers
aList
head si#e tail
%
**88 ++
3odes:• Contain # handles
• lin to next node
• lin to previous node• lin to stored object
• 0in s to next andprevious ma e it adoubly lin ed list
3odes:• Contain # handles
• lin to next node•
lin to previous node• lin to stored object• 0in s to next and
previous ma e it adoubly lin ed list
!ttributes:•
lin to 'irst item in the list• si;e o' the list• lin to last item in the list
!ttributes:•
lin to 'irst item in the list• si;e o' the list• lin to last item in the list
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
16/52
5ariations on 0in ed 0ists
0ists can be lin ed doubly as sho-n0ists can also be lin ed in one directiononly – attribute -ould not need lin to tail – node needs 'or-ard lin and pointer to data
only – last item in list has lin set to null0ists can be circularly lin ed – last node has lin to 'irst node
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
17/52
4sin a LinkedList
)iven the commandLinkedList addressSe uence = new LinkedList!";
4ses the LinkedList constructor tobuild an empty list
head si#e tail
0
addressSe uence
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
18/52
!ddin to the 0in ed 0ist
esults o' command 'or 'irst addaddressSe uence$add!anAddress%ounter";
head si#e tail
0
addressSe uence
12%.111.%45.444$ 1
• Successive adds• create more nodes
and data values•
adjust lin s
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
19/52
!ccessin 5alues in a 0in ed 0ist
ust use the $get method!!Address%ounter" addresssSe uence$get!inde&""$incre'ent%ount!";
! LinkedList has no array -ith an indexto access an elementet method must 7
–
be in athead
node – iterate throu h inde& nodes to 'ind match – return re'erence o' object in that nodeCommand then does cast andincre'ent%ount!"
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
20/52
!ccessin 5alues in a 0in ed 0ist
"o print successive values 'or the output-or !int i = .; i / addressSe uence$si#e!"; i00"Syste'$out$println!addressSe uence$get!i"";
si#e methoetermines limit of loop
co#nter
get!i" starts atfirst no e$ iterates
i times to reachesire no e
• 3ote that each get!i" must pass over thesame 'irst i1) nodes previously accessed
• "his is ine''icient
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
21/52
!ccessin 5alues in a 0in ed 0ist
!n alternative, more e''icient access al orithmList2terator it =
addressSe uence$list2terator!"; while !it$has3e&t!""
Syste'$out$println! it$ne&t!"";! List2terator is an object that iteratesacross the values in a list"he ne&t!" method does the 'ollo-in :
1. save handle to current node
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
22/52
Insertin 3odes !ny-here in a0in ed 0ist
ecall problem -ith ArrayList – can add only at end o' the list – lin ed list has capability to insert nodes any-here
8e can sayaddressSe uence$add!n4 new anAddress%ounter";8hich -ill 7 – build a ne- node – update head and tail lin s i' re/uired – update node handle lin s to place ne- node to be n th
item in the list – allocates memory 'or the data item
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
23/52
Choosin the &roper 0ist!l orithm E''iciency
"ime=e''iciency is not a real=time issue – rather an issue o' ho- many steps an
al orithm re/uires0inear time – time proportional to n – re'erred to as O>n?, order n
Constant time – expressed as O>1?
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
24/52
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
25/52
Conclusions on E''iciency
I' problem involves many accesses tointerior o' a se/uence – se/uence should be stored in an ArrayListI' problems involves many insertions,deletions not at end – se/uence should be stored in LinkedListI' neither o' these is the case – it doesn
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
26/52
3eed 'or a Stac
"he remainders are enerated in theopposite order that they must be outputI' -e -ere able to 7 – enerate them – hold on to them as enerated – access >display? them in the
reverse order "AE3 -e have used a stac
+
%
1
1 % +
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
27/52
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
28/52
Implementin a Stack Class
3ote use o' Stack class in source code,@i ure 12.(, implementation in @i ure 12.B
Implemented -ith 0in ed0ist attributevariable to store values – this is a has=a relationship, the Stack
has a LinkedList – contrast the is=a relationship
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
29/52
+ava
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
30/52
12.$ Example: 6uildin a QueueClass
In a /ueue, – ne- values are al-ays added at the 'ront or
head o' the list – values are removed 'rom the opposite end o'the list, the rear or tailExamples o' /ueues – chec out at supermar et – vehicles at toll booth – tic et line at moviesueue exhibits @irst=In=@irst=Out
behavior
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
31/52
ueues in a Computer System
8hen a process >pro ram? re/uires acertain resource – printer – dis access on a net-or – characters in a eyboard bu''erueue anipulation Operations
– is6'pty!" : returns true or -alse – -irst!" : returns copy o' value at 'ront – add!7" : adds a ne- value at rear o' /ueue – re'o7e!" : removes, returns value at 'ront
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
32/52
Implementin a Queue Class
Implement as a LinkedList attributevalue – insertions and deletions 'rom either end are
e''icient, occur in constant O>1? time – ood choiceImplement as an ArrayList attribute – poor choice – addin values at one end, removin at other
end re/uire multiple shi'ts
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
33/52
Implementin a Queue Class
6uild a Queue 'rom scratch – build a lin ed structure to store the /ueue
elements!ttributes re/uired – handle 'or the head node – handle 'or tail node – inte er to store number o' values in the
/ueue – use SinglyLinked3ode class, source code,
@i ure 12.
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
34/52
Queue Structure
'y9ead 'ySi#e 'y5ail
n
aQueue
. . .
. . .,al#e 0 ,al#e 1 ,al#e n-1
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
35/52
Queue Class ethods
Constructor – set 'y9ead , 'y5ail to null – set 'ySi#e to ;erois6'pty!" – return results o' comparison 'ySi#e == .-ront!" – return 'y9ead$get8alue!" ** unless empty
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
36/52
Queue Class ethods
add!" – create ne- node, update attribute variables – i' /ueue is empty, must also update 'y9ead re'o7e!" – must chec i' class not empty
other-ise 7 – save handle to 'irst object – adjust head to re'er to node – update 'ySi#e ote so#rce co e for
hole class$ /i #re 12.9
ote so#rce co e for
hole class$ /i #re 12.9
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
37/52
12.% !n Introduction to "rees
8e see a -ay to or ani;ed a lin edstructure so that 7 – elements can be searched more /uic ly than
in a linearly lin ed structure – also provide 'or easy insertion*deletion – permit access in less than O>n? timeecall binary search strate y
– loo in middle o' list – eep loo in in middle o' subset above or
belo- current location in list –
until tar et value 'ound
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
38/52
5isuali;e 6inary Search
1% 28 %5 49 *2 ** 80
ra n as a binary tree
4928
1% %5
**
*2 80
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
39/52
"ree "erminolo y
! tree consists o': – 'inite collection o' nodes – non empty tree has a root node – root node has no incomin lin s – every other node in the tree can be reached 'rom
the root by uni/ue se/uence o' lin s
4928
1% %5
**
*2 80
eaf no es
3i"lin no esarent
an
chil no es
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
40/52
!pplications o' "rees
)enealo ical tree – pictures a person
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
41/52
Examples o' 6inary "rees
Each node has at most t-o children4se'ul in modelin processes -here atest has only t-o possible outcomes – true or 'alse – coin toss, heads or tailsEach uni/ue path can be described by these/uence o' outcomesCan be applied to decision trees in expertsystems o' arti'icial intelli ence
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
42/52
Implementin 6inary "rees
6inary tree represented by multiplylin ed structure – each node has t-o lin s and a handle to the
data – one lin to le't child, other to the ri ht
8alue
'y8alue
'y:ight%hild 'yLe-t%hild
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
43/52
Implementin 6inary "rees
Declaration o' inary5ree3ode class
public class inary5ree3ode
<(( 'ethods go here(( Attributes
pri7ate inary5ree3ode 'yLe-t%hild4 'y:ight%hild;
pri7ate Object 'y8alue;>
ointers tos#ccee in no es
an le to store ,al#e
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
44/52
Implementin 6inary "rees
inary5ree3ode is only one o' theattributes o' a inary5ree class!lso need an attribute that eeps trac o'the number o' nodes in the tree
public class inary5ree e&tends Object<(( 'ethods
pri7ate inary5ree3ode 'y:oot; pri7ate int 'ySi#e;
>
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
45/52
5isuali;in a 6inary"ree
4*
*%1+
%
'y:oot 'ySi#e
a 5ree
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
46/52
6inary Search "rees
Search !l orithm1. Initiali;e a handle current3ode to the
node containin the root2. epeatedly do the 'ollo-in :
I' tar etGitem H current3ode.my5alue set current3ode current3ode.le'tChild
I' tar etGitem 9 current3ode.my5alueset current3ode current3ode.ri htChildElse
terminate repetition because tar etGitemhas been 'ound
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
47/52
"ree "raversals
! traversal is movin throu h the binary tree,visitin each node exactly once
– 'or no- order not important
"raverse !l orithm1. 5isit the root and process its contents2. "raverse the le't subtree
1. visit its root, process
2. traverse le't sub=sub tree#. traverse ri ht sub=sub tree#. "raverse the ri ht subtree
1. 7
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
48/52
"ree "raversal is ecursive
I' the binary tree is empty thendo nothin
Else0: "raverse the le't subtree3: 5isit the root
: "raverse the ri ht subtree
6he 7anchor7
6he in #cti,e step
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
49/52
"raversal Order
"hree possibilities 'or inductive step 70e't subtree, 3ode, i ht subtreethe inorder traversal
3ode, 0e't subtree, i ht subtreethe preorder traversal
0e't subtree, i ht subtree, 3odethe postorder traversal
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
50/52
Constructin 6inary Search"rees
epeatedly insert elements into a 6S" that isinitially emptyDescend tree, loo in 'or place to insert the
item – Set parent3ode = current3ode – chan e current3ode to its le't or ri ht child – i' value bein inserted is not in the tree,
current3ode -ill eventually become null and 7 – parent3ode -ill indicate the parent o' a ne- node
to contain the value
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
51/52
&art o' the &icture:Data Structures+ava provides standard classes – !rray0ist – 0in ed0istStandard classes used to solve variety o'problems8ise use o' these data structures simplysolutions to many problems!ttention should be iven to e''iciencyo' structure 'or particular tas at hand
-
8/16/2019 Updated 30 Apr Linked List and Arraylist Java311
52/52
Other Data Structures
Set inter'ace implemented by 9ashSet and 5reeSet classes
?ap inter'ace implemented by 5ree?ap and 9ash5able classes
%ollections class – variety o' utility methods 'or manipulatin
collections