8/19/2019 Linkedlist in Java
1/49
1
TCSS 342, Winter 2005
Lecture Notes
Linked List Implementation
Weiss Ch !, pp 1"3#205
Weiss Ch 1$, pp 53$#54"
8/19/2019 Linkedlist in Java
2/49
2
Collections
collection% an o&'ect that stores data inside it(aka a )data structure) the o&'ects stored are called elements some maintain an orderin*, some don+t some collections allo duplicates, some don+t an arra- is like a .er- crude )collection) t-pical operations% add element, remo.e element,
clear all elements, contains or /nd element, *et
sie most collections are &uilt ith particular kinds o
data, or particular operations on that data, inmind
eamples% java.util.ArrayList, java.util.HashMap,java.util.TreeSet
8/19/2019 Linkedlist in Java
3/49
3
a.a+s Collection interace
a.a pro.ides an interace java.util.Collection to represent man- kinds o collections It has theolloin* methods%
public boolean add(Object o)
ppends the speci/ed element to this collection
public void clear()
emo.es all o the elements o this collection
public boolean contains(Object o)eturns true i this collection contains the speci/ed element
public boolean containsAll(Collection coll)
eturns true i this collection contains all o the elements in
the speci/ed collection
8/19/2019 Linkedlist in Java
4/49
4
Collection interace,cont+d
public boolean isEpty()eturns true i this list contains no elements
public !terator iterator()
eturns a special o&'ect or eaminin* the elements o the
list in order 6seen later7
public boolean reove(Object o)
emo.es the /rst occurrence in this list o the speci/edelement
public int si"e()
eturns the num&er o elements in this list
public Object#$ toArray()
eturns an arra- containin* all o the elements rom this list
8/19/2019 Linkedlist in Java
5/49
5
n eample collection% List
list% an ordered se8uence o elements,each accessi&le &- a 0#&ased inde one o the most &asic collections
8/19/2019 Linkedlist in Java
6/49
6
List eatures
ORDERING% maintains order elements ereadded6ne elements are added to the end &- deault7
DUPLICATES% -es 6alloed7 OPERATIONS% add element to end o list, insert
element at *i.en inde, clear all elements,search or element, *et element at *i.en inde,
remo.e element at *i.en inde, *et sie some o these operations are ine9cient: 6seen later7
list mana*es its on sie( user o the list doesnot need to orr- a&out o.er/llin* it
8/19/2019 Linkedlist in Java
7/497
a.a+s List interace
a.a also has an interace java.util.List to represent a list o o&'ects It adds theolloin* methods to those in Collection%6a partial list7
public void add(int inde%& Object o)
Inserts the speci/ed element at the speci/ed position inthis list
public Object 'et(int inde%)eturns the element at the speci/ed position in this list
public int inde%O(Object o)
eturns the inde in this list o the /rst occurrence o thespeci/ed element, or * i the list does not contain it
8/19/2019 Linkedlist in Java
8/498
List interace, cont+d
public int last!nde%O(Object o)
eturns the inde in this list o the last occurrence o thespeci/ed element, or #1 i the list does not contain it
public Object reove(int inde%)
emo.es the o&'ect at the speci/ed position in this list
public Object set(int inde%& Object o)
eplaces the element at the speci/ed position in this listith the speci/ed element
Notice that the methods added to Collection &- List all deal ith indees( a list has indeeshile a *eneral collection ma- not
8/19/2019 Linkedlist in Java
9/499
Some list 8uestions
all o the list operations on the pre.ious slidecould &e perormed usin* an arra- instead:
open 8uestion% What are some reasons h-e mi*ht ant to use a list class, rather thanan arra-, to store our data;
thou*ht 8uestion%
8/19/2019 Linkedlist in Java
10/4910
rra- list
array list% a list implemented usin* anarra- to store the elements encapsulates arra- and = o elements 6sie7 in a.a% java.util.ArrayList hen -ou ant to use ArrayList, remem&er
to iport java.util.+,
8/19/2019 Linkedlist in Java
11/4911
ArrayList eatures
think o it as an auto#resiin* arra- that canhold an- t-pe o o&'ect, ith man-con.enient methods
maintains most o the &ene/ts o arra-s,such as ast random access
rees us rom some tedious operations onarra-s, such as slidin* elements andresiin*
can call toStrin' on an ArrayList to printits elements #*& -./& Marty Stepp& Hello$
8/19/2019 Linkedlist in Java
12/4912
Collections class
Class java.util.Collections has man- utilit-methods that do useul thin*s to collections
public static void copy(List dest& List src)
public static void ill(List list& Object value)public static Object a%(Collection coll)
public static Object in(Collection coll)
public static void reverse(List list)
public static void shule(List list)public static void sort(List list)
public static void s0ap(List list& int i& int j)
>ample%Collections.sort(yArrayList),
8/19/2019 Linkedlist in Java
13/49
8/19/2019 Linkedlist in Java
14/4914
?pen 8uestions
ased on the precedin* anal-sis, hen isan ArrayList a *ood collection to use;When is it a poor perormer;
Is there a a- that e could / some othe pro&lems ith the ArrayList;
Should e represent our list in a diDerenta-;
8/19/2019 Linkedlist in Java
15/4915
some ArrayList pro&lems
an insertion into a ull list causes a lar*ereallocation
an insertion to the ront )slides) don the
su&se8uent items 6slo:7 a remo.al also )slides) don su&se8uent
items
still need to use indeesEsu&scripts a lot somehat u*l- s-nta to use it
8/19/2019 Linkedlist in Java
16/4916
The underl-in* issue
the elements o an ArrayList are tooti*htl- attached( can+t easil- rearran*ethem
can e &reak the element stora*e apartinto a more d-namic and Fei&lestructure;
8/19/2019 Linkedlist in Java
17/4917
Nodes% o&'ects to storeelements
let+s make a special )node) t-pe o o&'ectthat represents a stora*e slot to hold oneelement o a list
each node ill keep a reerence to thenode ater it 6the )net) node7
the last node ill ha.e ne%t 11 null
6dran as E 7, si*ni-in* the end o the list
8/19/2019 Linkedlist in Java
18/4918
Node implementation
2+ Stores one eleent o a lin3ed list. +2public class 4ode 5
public Object element, public 4ode next,
public 4ode(Object eleent) 5
this(eleent& null),
6
public 4ode(Object eleent& 4ode ne%t) 5
this.eleent 1 eleent,
this.ne%t 1 ne%t,
6
6
8/19/2019 Linkedlist in Java
19/4919
Linked node pro&lems 6a7
Let+s eamine sample chains o nodesto*ether, and tr- to rite the correctcode or each
each Node stores an !nte'er o&'ect
1
&eore%
ater%
8/19/2019 Linkedlist in Java
20/49
20
Linked node pro&lems 6&7
2 &eore%
ater%
3
&eore%
ater%
8/19/2019 Linkedlist in Java
21/49
21
Linked node pro&lems 6c7
4 &eore%
ater%
5
&eore%
ater%
8/19/2019 Linkedlist in Java
22/49
22
Linked node pro&lems 6d7
! &eore%
ater%
$
&eore%
ater%
8/19/2019 Linkedlist in Java
23/49
23
Linked list
linked list% a list implemented usin* alinked se8uence o nodes the list onl- needs to keep a reerence to the
/rst node 6e mi*ht name it y7ront7 in a.a% java.util.Lin3edList
6&ut e+ll rite our on7
8/19/2019 Linkedlist in Java
24/49
24
Linked list implementation
2+ Models an entire lin3ed list. +2public class MyLin3edList 5
private 4ode y7ront,
public MyLin3edList() 5
y7ront 1 null,
6
2+ Methods go here +2
6
8/19/2019 Linkedlist in Java
25/49
8/19/2019 Linkedlist in Java
26/49
26
Let+s dra them to*ether
an add operation at the ront, &ack, and middle
a remo.e operation
a *et operation a set operation
an inde o 6searchin*7 operation
8/19/2019 Linkedlist in Java
27/49
27
nal-sis o Lin3edList runtime
?@>TI?Nadd to start o listadd to end o listadd at *i.en inde
clear*et/nd inde o an o&'ectremo.e /rst element
remo.e last elementremo.e at *i.en indesetsie
toStrin*
ANTIB> 6i*#?h7 ?617 O(n) O(n)
?617 O(n) O(n) ?617
O(n) O(n) O(n) O(n)
O(n)
8/19/2019 Linkedlist in Java
28/49
28
n optimiation% ySi"e
pro&lem% arra- list has a ?617 si"e method, &ut the linked list needs ?6n7time
solution% add a ySi"e /eld to our linkedlist hat chan*es must &e made to the
implementation o the methods o the linkedlist;
8/19/2019 Linkedlist in Java
29/49
29
.ariation% dumm-header
dmmy !eader% a ront nodeintentionall- let &lank y7ront ala-s reers to dumm- header
6y7ront
ill ne.er &enull
7 re8uires minor modi/cation to man- methods
surprisin*l-, makes implementation mucheasier
8/19/2019 Linkedlist in Java
30/49
8/19/2019 Linkedlist in Java
31/49
31
Gou&l-#linked lists
add a prev pointer to our 4ode class allos &ackard iteration 6orList!terator7
some methods need to &e modi/ed hen addin* or remo.in* a node, e must /
the prev and ne%t pointers to ha.e the
correct .alue: can make it easier to implement some
methods such as reove
8/19/2019 Linkedlist in Java
32/49
32
Com&inin* the approaches
Bost actual linked list implementationsare dou&l-#linked and use a dumm-header and dmmy tail
this actuall- makes a .er- cleanimplementation or all linked list methodsand pro.ides *ood e9cienc- or as man-
operations as possi&le
8/19/2019 Linkedlist in Java
33/49
33
Impro.ed Lin3edList runtime
?@>TI?Nadd to start o listadd to end o listadd at *i.en inde
clear*et/nd inde o an o&'ectremo.e /rst element
remo.e last elementremo.e at *i.en indesetsie
toStrin*
ANTIB> 6i*#?h7 ?617 ?617 O(n)
?617 O(n) O(n) ?617
?617 O(n) O(n) ?617
O(n)
8/19/2019 Linkedlist in Java
34/49
34
particularl- slo idiom
22 print every eleent o lin3ed listor (int i 1 9, i : list.size(), i;;) 5
Object eleent 1 list.get(i),
Syste.out.println(i ;
8/19/2019 Linkedlist in Java
35/49
35
The pro&lem o position
The code on the pre.ious slide is asteul&ecause it thros aa- the position each time e.er- call to 'et has to re#tra.erse the list:
it ould &e much &etter i e could somehokeep the list in place at each inde as elooped throu*h it
a.a uses special o&'ects to represent aposition o a collection as it+s &ein*eamined
these o&'ects are called )iterators)
8/19/2019 Linkedlist in Java
36/49
36
Iterators in a.a
interace java.util.!terator public boolean has4e%t()
eturns true i there are more elements tosee
public Object ne%t()eturns the net o&'ectin this collection, thenad.ances the iterator(thros an eception
i no more elementsremain
public void reove()Geletes the element that as
last returned &- ne%t 6not ala-s supported7
8/19/2019 Linkedlist in Java
37/49
37
Iterators on arra- lists
n iterator on an arra- list is simple( itmaintains an inde o its current node
iterators are not as useul on arra- lists Wh-;
What is the i*#?h o *et and set;
What is the i*#?h o add and remo.e; Goes the arra- list iterator impro.e this;
8/19/2019 Linkedlist in Java
38/49
38
Iterators on linked lists
an iterator on a linked list maintains 6atleast7 its current inde and a reerence tothat node
hen iterator() is called on a linked list,the iterator initiall- reers to the /rstnode 6inde 07
8/19/2019 Linkedlist in Java
39/49
8/19/2019 Linkedlist in Java
40/49
40
8/19/2019 Linkedlist in Java
41/49
41
Hiin* the slo LL idiom
22 print every eleent o the listor (int i 1 9, i : list.size(), i;;) 5
Object eleent 1 list.get(i),
Syste.out.println(i ;
8/19/2019 Linkedlist in Java
42/49
42
Iterator usa*e eample
MyLin3edList naes 1 ne0 MyLin3edList(),22 ... ill the list 0ith soe data ...
22 print every nae in the list& in upper case
Iterator itr = myList.iterator();0hile (
itr.hasNext()) 5
Strin' eleent 1 (Strin')itr.next(), Syste.out.println(eleent.to>pperCase()),6
22 reove strin's ro list that start 0ith
8/19/2019 Linkedlist in Java
43/49
43
ene/ts o iterators
speed up loops o.er linked lists+ elements What is the i*#?h o each iterator method;
pro.ide a uni/ed a- to eamine all
elements o a collection e.er- collection in a.a has an iterator method
in act, that+s the only *uaranteed a- to eaminethe elements o an- Collection 6see Slide 47
don+t need to look up diDerent collections+method names to see ho to eamine theirelements
don+t ha.e to use indees as much on lists
8/19/2019 Linkedlist in Java
44/49
44
Iterator is still not perect
22 print oddvalued eleents& 0ith their inde%es!terator itr 1 list.iterator(),
or (int i = 0; itr.has4e%t(), i;;) 5
int eleent 1 ((!nte'er)itr.ne%t()).int@alue(),
i (eleent - 11 *) Syste.out.println(i ;
8/19/2019 Linkedlist in Java
45/49
45
Bore iterator pro&lems
22 add a 9 ater any odd eleent
!terator itr 1 list.iterator(),
int i 1 9,
0hile (itr.has4e%t()) 5
int eleent 1 ((!nte'er)itr.ne%t()).int@alue(),
i (eleent - 11 *) list.add(i, new Integer(0)); // ails
6
can+t use the iterator to add, set element .alues6iterator is pro*rammed to crash i list is modi/ed7
the iterator speeds up 'et and reove loops onl- the iterator reall- should &e a&le to help us speed
up loops that add elements or set elements+ .alues:
8/19/2019 Linkedlist in Java
46/49
46
List!terator interace
a.a interace java.util.List!terator etends!terator to add these methods% public void add(Object o)
public int ne%t!nde%()
public int previous!nde%()
public void set(Object o)
List!terator is also a&le to iterate in re.erse% public boolean hasBrevious()
public Object previous()
*et a List!terator &- callin* these methods on theList% 6&oth ArrayList and Lin3edList ha.e them7 public List!terator list!terator()
!"#li$ ListIterator listIterator(int index)
8/19/2019 Linkedlist in Java
47/49
47
List!terator usa*e
22 print oddvalued eleents& 0ith their inde%es
or (ListIterator itr = list.listIterator();
itr.hasNext(); ) 5
int eleent 1 ((!nte'er)itr.ne%t()).int@alue(),
i (eleent - 11 *)
Syste.out.println(itr.!revio"sIndex() ;
8/19/2019 Linkedlist in Java
48/49
48
List!terator &ene/ts
usin* the List!terator internall- toimplement the methods o the linked listcan make the code cleaner and simpler%
public Object 'et(int inde%) 5
ListIterator itr = listIterator(index);
ret"rn itr.next();
6
should the code check the inde or
.alidit-;
8/19/2019 Linkedlist in Java
49/49
Summar-
lists are ordered, inte*er#indeedcollections that allo duplicates
lists are *ood or storin* elements in ordero insertion and tra.ersin* them in thatorder
linked lists are aster or add E remo.eoperations at the ront and &ack, &ut sloer
than arra- lists or ar&itrar- *et E setoperations
lists are &ad or searchin* or elements and