preparation data structures 05 chain linear_list
TRANSCRIPT
Images/cinvestav-1.jpg
Outline1 Iterators
InterfaceSeparate and Inner Class Iterator
2 IntroductionLinked RepresentationMemory Layout
3 OperationsIsEmpty()size()Get(Index)RemoveAdd
4 Can we simplify the code?
5 Other data structures based in the Linked List
2 / 79
Images/cinvestav-1.jpg
Iterator Method
ScenarioWe often want to access every item in a data structure or collection inturn...
Example with the array representation1 int listSize = SomeList.size();2 for (int i = 0; i < listSize; i++)3 System.out.println(SomeList.get(i));
3 / 79
Images/cinvestav-1.jpg
Iterator Method
ScenarioWe often want to access every item in a data structure or collection inturn...
Example with the array representation1 int listSize = SomeList.size();2 for (int i = 0; i < listSize; i++)3 System.out.println(SomeList.get(i));
3 / 79
Images/cinvestav-1.jpg
Motivation
QuestionWhat if we have a get that is really complex?
For example the get in a Chain ListWe will see that it has complexity O(n)!!!
Previous CodeWhat a waste of time!!! O
(n2)
!!!!
4 / 79
Images/cinvestav-1.jpg
Motivation
QuestionWhat if we have a get that is really complex?
For example the get in a Chain ListWe will see that it has complexity O(n)!!!
Previous CodeWhat a waste of time!!! O
(n2)
!!!!
4 / 79
Images/cinvestav-1.jpg
Motivation
QuestionWhat if we have a get that is really complex?
For example the get in a Chain ListWe will see that it has complexity O(n)!!!
Previous CodeWhat a waste of time!!! O
(n2)
!!!!
4 / 79
Images/cinvestav-1.jpg
Then
Something NotableIteration is such a common operation that we could include it as part ofthe ADT list.
HoweverWe do not want to add another operation to the ADT each time we thinkof another way to use an iteration.
5 / 79
Images/cinvestav-1.jpg
Then
Something NotableIteration is such a common operation that we could include it as part ofthe ADT list.
HoweverWe do not want to add another operation to the ADT each time we thinkof another way to use an iteration.
5 / 79
Images/cinvestav-1.jpg
Outline1 Iterators
InterfaceSeparate and Inner Class Iterator
2 IntroductionLinked RepresentationMemory Layout
3 OperationsIsEmpty()size()Get(Index)RemoveAdd
4 Can we simplify the code?
5 Other data structures based in the Linked List
6 / 79
Images/cinvestav-1.jpg
In Java at java.util we have the interface Iterator
Interface
package j a v a . u t i l ;p u b l i c i n t e r f a c e I t e r a t o r <Item> {
p u b l i c boo l ean hasNext ( ) ;
p u b l i c I tem next ( ) ;
// Opt i ona l methodp u b l i c vo i d remove ( ) ;
} // end I t e r a t o r
7 / 79
Images/cinvestav-1.jpg
Explanation
public boolean hasNext()It detects whether this iterator has completed its traversal and gonebeyond the last entry in the collection of data.It returns true if the iterator has another entry to return.
public T next()It retrieves the next entry in the collection and advances this iteratorby one position.It returns a reference to the next entry in the iteration, if one existsIt throws NoSuchElementException if the iterator had reached theend already, that is, if hasNext() is false.
8 / 79
Images/cinvestav-1.jpg
Explanation
public boolean hasNext()It detects whether this iterator has completed its traversal and gonebeyond the last entry in the collection of data.It returns true if the iterator has another entry to return.
public T next()It retrieves the next entry in the collection and advances this iteratorby one position.It returns a reference to the next entry in the iteration, if one existsIt throws NoSuchElementException if the iterator had reached theend already, that is, if hasNext() is false.
8 / 79
Images/cinvestav-1.jpg
Explanation
public boolean hasNext()It detects whether this iterator has completed its traversal and gonebeyond the last entry in the collection of data.It returns true if the iterator has another entry to return.
public T next()It retrieves the next entry in the collection and advances this iteratorby one position.It returns a reference to the next entry in the iteration, if one existsIt throws NoSuchElementException if the iterator had reached theend already, that is, if hasNext() is false.
8 / 79
Images/cinvestav-1.jpg
Explanation
public boolean hasNext()It detects whether this iterator has completed its traversal and gonebeyond the last entry in the collection of data.It returns true if the iterator has another entry to return.
public T next()It retrieves the next entry in the collection and advances this iteratorby one position.It returns a reference to the next entry in the iteration, if one existsIt throws NoSuchElementException if the iterator had reached theend already, that is, if hasNext() is false.
8 / 79
Images/cinvestav-1.jpg
Explanation
public boolean hasNext()It detects whether this iterator has completed its traversal and gonebeyond the last entry in the collection of data.It returns true if the iterator has another entry to return.
public T next()It retrieves the next entry in the collection and advances this iteratorby one position.It returns a reference to the next entry in the iteration, if one existsIt throws NoSuchElementException if the iterator had reached theend already, that is, if hasNext() is false.
8 / 79
Images/cinvestav-1.jpg
Explanation
public void remove()It removes from the collection of data the last entry that next()returned.Precondition: next() has been called, and remove() has not been
called since then.I It throws IllegalStateException if next() has not been
called, or if remove() was called already after the lastcall to next().
9 / 79
Images/cinvestav-1.jpg
Explanation
public void remove()It removes from the collection of data the last entry that next()returned.Precondition: next() has been called, and remove() has not been
called since then.I It throws IllegalStateException if next() has not been
called, or if remove() was called already after the lastcall to next().
9 / 79
Images/cinvestav-1.jpg
Explanation
public void remove()It removes from the collection of data the last entry that next()returned.Precondition: next() has been called, and remove() has not been
called since then.I It throws IllegalStateException if next() has not been
called, or if remove() was called already after the lastcall to next().
9 / 79
Images/cinvestav-1.jpg
Effect in a list
Before next()Joes Piotor Iterator cursor Jen Jess Marius
After next()Joes Piotor Jen Iterator cursor Jess Marius
Effect of remove()Joes Piotor Iterator cursor Jess Marius
10 / 79
Images/cinvestav-1.jpg
Effect in a list
Before next()Joes Piotor Iterator cursor Jen Jess Marius
After next()Joes Piotor Jen Iterator cursor Jess Marius
Effect of remove()Joes Piotor Iterator cursor Jess Marius
10 / 79
Images/cinvestav-1.jpg
Effect in a list
Before next()Joes Piotor Iterator cursor Jen Jess Marius
After next()Joes Piotor Jen Iterator cursor Jess Marius
Effect of remove()Joes Piotor Iterator cursor Jess Marius
10 / 79
Images/cinvestav-1.jpg
NO FREE LUNCH!!!
RemarkSome details of using an iterator depend on the approach used toimplement the iterator methods.
We can do the followingA possible, but not optimal, way to provide an ADT with traversaloperations is to define them as ADT operations.
I For example, if ListInterface extends Iterator, a list object wouldhave iterator methods as well as list methods.
I PROBLEM!!! What if you want to have two or more iterators over theobject list making different things at the same time!!!
11 / 79
Images/cinvestav-1.jpg
NO FREE LUNCH!!!
RemarkSome details of using an iterator depend on the approach used toimplement the iterator methods.
We can do the followingA possible, but not optimal, way to provide an ADT with traversaloperations is to define them as ADT operations.
I For example, if ListInterface extends Iterator, a list object wouldhave iterator methods as well as list methods.
I PROBLEM!!! What if you want to have two or more iterators over theobject list making different things at the same time!!!
11 / 79
Images/cinvestav-1.jpg
NO FREE LUNCH!!!
RemarkSome details of using an iterator depend on the approach used toimplement the iterator methods.
We can do the followingA possible, but not optimal, way to provide an ADT with traversaloperations is to define them as ADT operations.
I For example, if ListInterface extends Iterator, a list object wouldhave iterator methods as well as list methods.
I PROBLEM!!! What if you want to have two or more iterators over theobject list making different things at the same time!!!
11 / 79
Images/cinvestav-1.jpg
NO FREE LUNCH!!!
RemarkSome details of using an iterator depend on the approach used toimplement the iterator methods.
We can do the followingA possible, but not optimal, way to provide an ADT with traversaloperations is to define them as ADT operations.
I For example, if ListInterface extends Iterator, a list object wouldhave iterator methods as well as list methods.
I PROBLEM!!! What if you want to have two or more iterators over theobject list making different things at the same time!!!
11 / 79
Images/cinvestav-1.jpg
Outline1 Iterators
InterfaceSeparate and Inner Class Iterator
2 IntroductionLinked RepresentationMemory Layout
3 OperationsIsEmpty()size()Get(Index)RemoveAdd
4 Can we simplify the code?
5 Other data structures based in the Linked List
12 / 79
Images/cinvestav-1.jpg
Solution
We can haveSeparate class iteratorInner Class Iterator
For separate class iterator, we have stuff like thisIterator<String> nameIterator = newSeparateIterator<String>(nameList);
13 / 79
Images/cinvestav-1.jpg
Solution
We can haveSeparate class iteratorInner Class Iterator
For separate class iterator, we have stuff like thisIterator<String> nameIterator = newSeparateIterator<String>(nameList);
13 / 79
Images/cinvestav-1.jpg
Solution
We can haveSeparate class iteratorInner Class Iterator
For separate class iterator, we have stuff like thisIterator<String> nameIterator = newSeparateIterator<String>(nameList);
13 / 79
Images/cinvestav-1.jpg
Multiple Iterators
ThusExternal Iterators provides a solution to multiple iterators
However
Huge ProblemWe can only access the list through the public methods:
What if they are not enough?
15 / 79
Images/cinvestav-1.jpg
Multiple IteratorsThusExternal Iterators provides a solution to multiple iterators
However
Object Iterator from separate class iterators
Object from class list
list
LouPegMegME
IteratorCursor
NextPosition2
Huge ProblemWe can only access the list through the public methods:
What if they are not enough?15 / 79
Images/cinvestav-1.jpg
Separate Iterator CodeCode
impor t j a v a . u t i l . I t e r a t o r ;impor t j a v a . u t i l . NoSuchElementExcept ion ;
p u b l i c c l a s s S e p a r a t e I t e r a t o r <Item>implements I t e r a t o r <Item> {
p r i v a t e L i n e a r L i s t <Item> l i s t ;// p o s i t i o n o f e n t r y l a s t r e t u r n e d by next ( )p r i v a t e i n t n e x t P o s i t i o n ;// needed by removep r i v a t e boo l ean wasNextCa l l ed ;
p u b l i c S e p a r a t e I t e r a t o r ( L i s t L i s t <Item> aL i s t ) {// A l l t ha t i t i m p l i e s} // end c o n s t r u c t o r
< Imp l ementa t i on s o f the methods hasNext , . . .nex t , and remove go he r e > . . .} // end S e p a r a t e I t e r a t o r
16 / 79
Images/cinvestav-1.jpg
We need a better solution!!!
Declare a inner classSo you can have direct access to the protected or private elements in theobject!!!
Actually you have something like this
17 / 79
Images/cinvestav-1.jpg
We need a better solution!!!
Declare a inner classSo you can have direct access to the protected or private elements in theobject!!!
Actually you have something like this
Object Iterator from Inner class iterators
Object from class array list
Lou Peg Meg ME
nextPosition2
17 / 79
Images/cinvestav-1.jpg
Inner Class Code
Codeimpor t j a v a . u t i l . I t e r a t o r ;impor t j a v a . u t i l . NoSuchElementExcept ion ;
p u b l i c c l a s s A r r a y L i s t W i t h I t e r a t o r <T>implements L i s t W i t h I t e r a t o r I n t e r f a c e <T> {
// ALL the code f o r a r r a y l i n e a r l i s t
p r i v a t e c l a s s I t e r a t o r F o r A r r a y L i s timp lements I t e r a t o r <T> {
p r i v a t e i n t n e x t I n d e x ;p r i v a t e boo l ean wasNextCa l l ed ;
p r i v a t e I t e r a t o r F o r A r r a y L i s t ( ) {n e x t I n d e x = 0 ;wasNextCa l l ed = f a l s e ;
} // end d e f a u l t c o n s t r u c t o r
< I m p l e m e n t a t i o n s o f the methods i n thei n t e r f a c e I t e r a t o r go he r e > . . . }// end I t e r a t o r F o r A r r a y L i s t
} // end A r r a y L i s t W i t h I t e r a t o r
18 / 79
Images/cinvestav-1.jpg
So, we have...
AdvantagesIt is a way of logically grouping classes that are only used in one place.It increases encapsulationIt can lead to more readable and maintainable code.
ExampleArrayListWithIterator<Integers> SOME = newArrayListWithIterator<Integers>();ArrayListWithIterator.IteratorForArrayList fl = SOME. newIteratorForArrayList();
19 / 79
Images/cinvestav-1.jpg
So, we have...
AdvantagesIt is a way of logically grouping classes that are only used in one place.It increases encapsulationIt can lead to more readable and maintainable code.
ExampleArrayListWithIterator<Integers> SOME = newArrayListWithIterator<Integers>();ArrayListWithIterator.IteratorForArrayList fl = SOME. newIteratorForArrayList();
19 / 79
Images/cinvestav-1.jpg
So, we have...
AdvantagesIt is a way of logically grouping classes that are only used in one place.It increases encapsulationIt can lead to more readable and maintainable code.
ExampleArrayListWithIterator<Integers> SOME = newArrayListWithIterator<Integers>();ArrayListWithIterator.IteratorForArrayList fl = SOME. newIteratorForArrayList();
19 / 79
Images/cinvestav-1.jpg
So, we have...
AdvantagesIt is a way of logically grouping classes that are only used in one place.It increases encapsulationIt can lead to more readable and maintainable code.
ExampleArrayListWithIterator<Integers> SOME = newArrayListWithIterator<Integers>();ArrayListWithIterator.IteratorForArrayList fl = SOME. newIteratorForArrayList();
19 / 79
Images/cinvestav-1.jpg
Outline1 Iterators
InterfaceSeparate and Inner Class Iterator
2 IntroductionLinked RepresentationMemory Layout
3 OperationsIsEmpty()size()Get(Index)RemoveAdd
4 Can we simplify the code?
5 Other data structures based in the Linked List
20 / 79
Images/cinvestav-1.jpg
Linked Representation
StorageList elements are stored, in memory, in an arbitrary order.
How you move through itExplicit information (called a link) is used to go from one element to thenext.
21 / 79
Images/cinvestav-1.jpg
Linked Representation
StorageList elements are stored, in memory, in an arbitrary order.
How you move through itExplicit information (called a link) is used to go from one element to thenext.
21 / 79
Images/cinvestav-1.jpg
Outline1 Iterators
InterfaceSeparate and Inner Class Iterator
2 IntroductionLinked RepresentationMemory Layout
3 OperationsIsEmpty()size()Get(Index)RemoveAdd
4 Can we simplify the code?
5 Other data structures based in the Linked List
22 / 79
Images/cinvestav-1.jpg
Memory Layout
We have the following
C A E D B
firstNode
FirstLast pointer (or link) from E is null
ThusYou can use a variable firstNode to get to the first element in the LinkedList.
23 / 79
Images/cinvestav-1.jpg
Memory Layout
We have the following
C A E D B
firstNode
FirstLast pointer (or link) from E is null
ThusYou can use a variable firstNode to get to the first element in the LinkedList.
23 / 79
Images/cinvestav-1.jpg
Memory Layout
We have the following
C A E D B
firstNode
FirstLast pointer (or link) from E is null
ThusYou can use a variable firstNode to get to the first element in the LinkedList.
23 / 79
Images/cinvestav-1.jpg
Normal Way To Draw A Linked List
Example
CA EDB
firstNode
Link or pointer field of node
Data field of node
NULL
24 / 79
Images/cinvestav-1.jpg
Actually, we know this as a Chain
FirstA chain is a linked list in which each node represents one element.
SecondThere is a link or pointer from one element to the next.
ThirdThe last node has a null pointer.
25 / 79
Images/cinvestav-1.jpg
Actually, we know this as a Chain
FirstA chain is a linked list in which each node represents one element.
SecondThere is a link or pointer from one element to the next.
ThirdThe last node has a null pointer.
25 / 79
Images/cinvestav-1.jpg
Actually, we know this as a Chain
FirstA chain is a linked list in which each node represents one element.
SecondThere is a link or pointer from one element to the next.
ThirdThe last node has a null pointer.
25 / 79
Images/cinvestav-1.jpg
Code for ChainNode
Code
package L i n e a r L i s t ;// Us ing Gene r i c i n Javac l a s s ChainNode<Item>{
// package data membersp r o t e c t e d Item e lement ;p r o t e c t e d ChainNode next ;// c o n s t r u c t o r s and methods come he r e
}
26 / 79
Images/cinvestav-1.jpg
The Constructors for ChainNode
A classic one
package L i n e a r L i s t ;// Us ing Gene r i c i n Javap u b l i c ChainNode ( ){
// Set the next nodet h i s . e l ement = n u l l ;t h i s . nex t = n u l l ;
}
p u b l i c ChainNode ( Item elem ){// Set e l ementt h i s . e l ement = elem ;t h i s . nex t = n u l l ;
}
27 / 79
Images/cinvestav-1.jpg
What about the Class Chain?
Code
/∗∗ l i n k e d imp l ementa t i on o f L i n e a r L i s t ∗/package i n f r a s t r u c t u r e s ;impor t j a v a . u t i l . ∗ ; // has I t e r a t o rp u b l i c c l a s s Chain<Item> implements L i n e a r L i s t <Item>{// data membersp r o t e c t e d ChainNode<Item> f i r s tN o d e ;p r o t e c t e d i n t s i z e ;
// methods o f Chain come he r e}
28 / 79
Images/cinvestav-1.jpg
In addition!!! Constructors!!!Code
p u b l i c Chain<Item> ( i n t i n i t i a l C a p a c i t y ){
// the d e f a u l t i n i t i a l v a l u e s o f f i r s t N o d e and s i z e// a r e n u l l and 0 , r e s p e c t i v e l y
}
A simple examplepublic Chain<Item> ()
{this.firstNode = new ChainNode<Item>();this.size = 0;
}29 / 79
Images/cinvestav-1.jpg
In addition!!! Constructors!!!Code
p u b l i c Chain<Item> ( i n t i n i t i a l C a p a c i t y ){
// the d e f a u l t i n i t i a l v a l u e s o f f i r s t N o d e and s i z e// a r e n u l l and 0 , r e s p e c t i v e l y
}
A simple examplepublic Chain<Item> ()
{this.firstNode = new ChainNode<Item>();this.size = 0;
}29 / 79
Images/cinvestav-1.jpg
Outline1 Iterators
InterfaceSeparate and Inner Class Iterator
2 IntroductionLinked RepresentationMemory Layout
3 OperationsIsEmpty()size()Get(Index)RemoveAdd
4 Can we simplify the code?
5 Other data structures based in the Linked List
30 / 79
Images/cinvestav-1.jpg
IsEmpty()
Really Simple Code
/∗∗ @re tu rn t r u e i f f l i s t i s empty ∗/p u b l i c boo l ean isEmpty ( )
{ r e t u r n s i z e == 0 ;}
31 / 79
Images/cinvestav-1.jpg
Outline1 Iterators
InterfaceSeparate and Inner Class Iterator
2 IntroductionLinked RepresentationMemory Layout
3 OperationsIsEmpty()size()Get(Index)RemoveAdd
4 Can we simplify the code?
5 Other data structures based in the Linked List
32 / 79
Images/cinvestav-1.jpg
size()
Really Simple Code
/∗∗ @re tu rn c u r r e n t number o f e l ement s i n l i s t ∗/p u b l i c i n t s i z e ( )
{ r e t u r n s i z e ; }
33 / 79
Images/cinvestav-1.jpg
Outline1 Iterators
InterfaceSeparate and Inner Class Iterator
2 IntroductionLinked RepresentationMemory Layout
3 OperationsIsEmpty()size()Get(Index)RemoveAdd
4 Can we simplify the code?
5 Other data structures based in the Linked List
34 / 79
Images/cinvestav-1.jpg
Operations: Get
Example
CA EDB
firstNode
Link or pointer field of node
Data field of node
NULL
What to do to implement Get1 Check Index2 Move to the correct position
I For example: TempNode = firstNode.next.next.next.I You actually use a loop.
3 return TempNode.element
35 / 79
Images/cinvestav-1.jpg
Operations: Get
Example
CA EDB
firstNode
Link or pointer field of node
Data field of node
NULL
What to do to implement Get1 Check Index2 Move to the correct position
I For example: TempNode = firstNode.next.next.next.I You actually use a loop.
3 return TempNode.element
35 / 79
Images/cinvestav-1.jpg
Process
Check Index
0 ≤ index ≤ size − 1 (1)
Negate the statement to use itHow?
36 / 79
Images/cinvestav-1.jpg
Process
Check Index
0 ≤ index ≤ size − 1 (1)
Negate the statement to use itHow?
36 / 79
Images/cinvestav-1.jpg
Move to the correct place
How?
CA EDB
firstNode NULL
TempNode=firstNode
37 / 79
Images/cinvestav-1.jpg
Move to the correct place
Index == 2
CA EDB
firstNode NULL
TempNode=firstNode
index==2
38 / 79
Images/cinvestav-1.jpg
Move to the correct place
Index == 2
CA EDB
firstNode NULL
TempNode=TempNode.next
index==2
39 / 79
Images/cinvestav-1.jpg
Move to the correct place
Index == 2
CA EDB
firstNode NULL
TempNode=TempNode.next
index==2
40 / 79
Images/cinvestav-1.jpg
Move to the correct place
Index == 2
CA EDB
firstNode NULL
return TempNode.element
index==2
41 / 79
Images/cinvestav-1.jpg
Code
Here is the method
p u b l i c <Item> get ( i n t i nd ex ){ChainNode<Item> TempNode ;// Check a lwaysi f ( t h i s . s i z e == 0) r e t u r n n u l l ;i f ( index <0 | | index>t h i s . s i z e −1){
System . out . p r i n t l n ( " I ndex ␣ out ␣ o f ␣bound " ) ;System . e x i t ( 0 ) ;
}//Move to the c o r r e c t p o s i t i o nTempNode = t h i s . f i r s t N o d e ;f o r ( i n t i=0 ; i<i ndex ; i ++){
TempNode = TempNode . nex t ;}r e t u r n TempNode . e l ement ;
}
42 / 79
Images/cinvestav-1.jpg
Outline1 Iterators
InterfaceSeparate and Inner Class Iterator
2 IntroductionLinked RepresentationMemory Layout
3 OperationsIsEmpty()size()Get(Index)RemoveAdd
4 Can we simplify the code?
5 Other data structures based in the Linked List
43 / 79
Images/cinvestav-1.jpg
Now, Remove
We have two casesAny ideas?
Case IRemoving from the beginning.
Case IIRemove from the middle.
44 / 79
Images/cinvestav-1.jpg
Now, Remove
We have two casesAny ideas?
Case IRemoving from the beginning.
Case IIRemove from the middle.
44 / 79
Images/cinvestav-1.jpg
Now, Remove
We have two casesAny ideas?
Case IRemoving from the beginning.
Case IIRemove from the middle.
44 / 79
Images/cinvestav-1.jpg
Case I: Remove(0)
Process1 if index == 0 do
1 TempNode = firstNode2 firstNode=firstNode.next3 TempNode.next=NULL4 return TempNode.element
45 / 79
Images/cinvestav-1.jpg
Case I: Remove(0)
Process1 if index == 0 do
1 TempNode = firstNode2 firstNode=firstNode.next3 TempNode.next=NULL4 return TempNode.element
45 / 79
Images/cinvestav-1.jpg
Case I: Remove(0)
Process1 if index == 0 do
1 TempNode = firstNode2 firstNode=firstNode.next3 TempNode.next=NULL4 return TempNode.element
45 / 79
Images/cinvestav-1.jpg
Case I: Remove(0)
Process1 if index == 0 do
1 TempNode = firstNode2 firstNode=firstNode.next3 TempNode.next=NULL4 return TempNode.element
45 / 79
Images/cinvestav-1.jpg
Case I: Remove(0)
Process1 if index == 0 do
1 TempNode = firstNode2 firstNode=firstNode.next3 TempNode.next=NULL4 return TempNode.element
45 / 79
Images/cinvestav-1.jpg
Process
return TempNode.element
CA EDB
firstNode NULL
return TempNode.elementNULL
49 / 79
Images/cinvestav-1.jpg
Case II: Remove(2)
Process1 Check Index2 Starting at the first node3 TempNode=firstNode;4 Loop doing
1 beforeNode=TempNode;2 TempNode=TempNode.next;
5 before.next = TempNode.next6 TempNode.next = NULL7 return TempNode.element
50 / 79
Images/cinvestav-1.jpg
Case II: Remove(2)
Process1 Check Index2 Starting at the first node3 TempNode=firstNode;4 Loop doing
1 beforeNode=TempNode;2 TempNode=TempNode.next;
5 before.next = TempNode.next6 TempNode.next = NULL7 return TempNode.element
50 / 79
Images/cinvestav-1.jpg
Case II: Remove(2)
Process1 Check Index2 Starting at the first node3 TempNode=firstNode;4 Loop doing
1 beforeNode=TempNode;2 TempNode=TempNode.next;
5 before.next = TempNode.next6 TempNode.next = NULL7 return TempNode.element
50 / 79
Images/cinvestav-1.jpg
Case II: Remove(2)
Process1 Check Index2 Starting at the first node3 TempNode=firstNode;4 Loop doing
1 beforeNode=TempNode;2 TempNode=TempNode.next;
5 before.next = TempNode.next6 TempNode.next = NULL7 return TempNode.element
50 / 79
Images/cinvestav-1.jpg
Case II: Remove(2)
Process1 Check Index2 Starting at the first node3 TempNode=firstNode;4 Loop doing
1 beforeNode=TempNode;2 TempNode=TempNode.next;
5 before.next = TempNode.next6 TempNode.next = NULL7 return TempNode.element
50 / 79
Images/cinvestav-1.jpg
Case II: Remove(2)
Process1 Check Index2 Starting at the first node3 TempNode=firstNode;4 Loop doing
1 beforeNode=TempNode;2 TempNode=TempNode.next;
5 before.next = TempNode.next6 TempNode.next = NULL7 return TempNode.element
50 / 79
Images/cinvestav-1.jpg
Case II: Remove(2)
Process1 Check Index2 Starting at the first node3 TempNode=firstNode;4 Loop doing
1 beforeNode=TempNode;2 TempNode=TempNode.next;
5 before.next = TempNode.next6 TempNode.next = NULL7 return TempNode.element
50 / 79
Images/cinvestav-1.jpg
Case II: Remove(2)
Process1 Check Index2 Starting at the first node3 TempNode=firstNode;4 Loop doing
1 beforeNode=TempNode;2 TempNode=TempNode.next;
5 before.next = TempNode.next6 TempNode.next = NULL7 return TempNode.element
50 / 79
Images/cinvestav-1.jpg
Case II: Remove(2)
Process1 Check Index2 Starting at the first node3 TempNode=firstNode;4 Loop doing
1 beforeNode=TempNode;2 TempNode=TempNode.next;
5 before.next = TempNode.next6 TempNode.next = NULL7 return TempNode.element
50 / 79
Images/cinvestav-1.jpg
Process: index == 2
beforeNode=TempNode;TempNode=TempNode.next;
CA EDB
firstNode NULL
beforeNode=TempNode TempNode=TempNode.next
index==2
52 / 79
Images/cinvestav-1.jpg
Process: index == 2
beforeNode=TempNode;TempNode=TempNode.next;
CA EDB
firstNode NULL
beforeNode=TempNode TempNode=TempNode.next
index==2
53 / 79
Images/cinvestav-1.jpg
Process: index == 2
before.next = TempNode.next
CA EDB
firstNode NULL
beforeNode.next=TempNode.next
54 / 79
Images/cinvestav-1.jpg
Process: index == 2
TempNode.next = NULL
CA EDB
firstNode NULL
TempNode=TempNode.nextNULL
55 / 79
Images/cinvestav-1.jpg
Process: index == 2
TempNode.next = NULL
CA EDB
firstNode NULL
return TempNode.elementNULL
56 / 79
Images/cinvestav-1.jpg
Outline1 Iterators
InterfaceSeparate and Inner Class Iterator
2 IntroductionLinked RepresentationMemory Layout
3 OperationsIsEmpty()size()Get(Index)RemoveAdd
4 Can we simplify the code?
5 Other data structures based in the Linked List
57 / 79
Images/cinvestav-1.jpg
Now, Add
We have four casesAny ideas?
Case IThe Chain is Empty
Case IIAdd at the beginning.
58 / 79
Images/cinvestav-1.jpg
Now, Add
We have four casesAny ideas?
Case IThe Chain is Empty
Case IIAdd at the beginning.
58 / 79
Images/cinvestav-1.jpg
Now, Add
We have four casesAny ideas?
Case IThe Chain is Empty
Case IIAdd at the beginning.
58 / 79
Images/cinvestav-1.jpg
Now, Add
We have four casesAny ideas?
Case IIIAdd at the middle.
Case IVAdd at the end.
59 / 79
Images/cinvestav-1.jpg
Now, Add
We have four casesAny ideas?
Case IIIAdd at the middle.
Case IVAdd at the end.
59 / 79
Images/cinvestav-1.jpg
Now, Add
We have four casesAny ideas?
Case IIIAdd at the middle.
Case IVAdd at the end.
59 / 79
Images/cinvestav-1.jpg
Add at an empty list
Steps1 Create a node to store the element, NewNode2 Then assign firstNode = NewNode
61 / 79
Images/cinvestav-1.jpg
Add at an empty list
Steps1 Create a node to store the element, NewNode2 Then assign firstNode = NewNode
61 / 79
Images/cinvestav-1.jpg
Add at an empty list
Steps1 Create a node to store the element, NewNode2 Then assign firstNode = NewNode
firstNode
K
NULL
61 / 79
Images/cinvestav-1.jpg
Add At the Beginning
Steps1 Create a node to store the element, NewNode2 Do NewNode.next = firstNode3 Then reassign firstNode = NewNode4 Then, size = size +1
62 / 79
Images/cinvestav-1.jpg
Add At the Beginning
Steps1 Create a node to store the element, NewNode2 Do NewNode.next = firstNode3 Then reassign firstNode = NewNode4 Then, size = size +1
62 / 79
Images/cinvestav-1.jpg
Add At the Beginning
Steps1 Create a node to store the element, NewNode2 Do NewNode.next = firstNode3 Then reassign firstNode = NewNode4 Then, size = size +1
62 / 79
Images/cinvestav-1.jpg
Add At the Beginning
Steps1 Create a node to store the element, NewNode2 Do NewNode.next = firstNode3 Then reassign firstNode = NewNode4 Then, size = size +1
62 / 79
Images/cinvestav-1.jpg
Add At the Beginning
Steps1 Create a node to store the element, NewNode2 Do NewNode.next = firstNode3 Then reassign firstNode = NewNode4 Then, size = size +1
CA EDB
firstNode
NULL
K
62 / 79
Images/cinvestav-1.jpg
What about the other case?
Do you have an idea?Add at the Middle.Add at the end.
63 / 79
Images/cinvestav-1.jpg
What about the other methods?
Linear ListAbstractDataType LinearList{
instancesordered finite collections of zero or more elements
operationsisEmpty(): return true iff the list is empty, false otherwisesize(): return the list size (i.e., number of elements in the list)get(index): return the element with the “index” indexindexOf(x): return the index of the first occurrence of x in the list, return -1
if x is not in the listremove(index): remove and return the indexth element, elements with higher
index have their index reduced by 1add(theIndex, x): insert x as the index of th element, elements with
theIndex ≥ index have their index increased by 1output(): output the list elements from left to right
}
64 / 79
Images/cinvestav-1.jpg
Complexity of Linked List
We haveDynamic Array Linked List
Amortized AnalysisIndexing O (1) O (n)Search O (n) O (n)
Add/Remove at the beginning O (n) O (1)Add/Remove at the middle O (n) Search Time
+O (1)Space Complexity O (n) O (n)
65 / 79
Images/cinvestav-1.jpg
Average Performance with Each Implementation on a SlowMachine!!!
40,000 Operations each type on a 350Mhz PCOperation FastArrayLinearList Chainaverage get 5.6 ms 157 secaverage adds 5.8 sec 115 sec
average removes 5.8 sec 157 sec
66 / 79
Images/cinvestav-1.jpg
Can we simplify the code?
How?We would like to simplify the code.... How?
What about
67 / 79
Images/cinvestav-1.jpg
Can we simplify the code?
How?We would like to simplify the code.... How?
What about
CA EDBheaderNode NULL
67 / 79
Images/cinvestav-1.jpg
Can we simplify the code?
Then, the empty list looks likeheaderNode
ThusThis simplify a lot the code because everything is a middle node
68 / 79
Images/cinvestav-1.jpg
Can we simplify the code?
Then, the empty list looks likeheaderNode
ThusThis simplify a lot the code because everything is a middle node
68 / 79
Images/cinvestav-1.jpg
Here, we need to have the following changes
We need to add the following to the class
/∗∗ l i n k e d imp l ementa t i on o f L i n e a r L i s t ∗/package i n f r a s t r u c t u r e s ;impor t j a v a . u t i l . ∗ ; // has I t e r a t o rp u b l i c c l a s s Chain<Item> implements L i n e a r L i s t <Item>{// data membersp r o t e c t e d ChainNode<Item> f i r s tN o d e ;p r o t e c t e d ChainNode<Item> la s tNode ;p r o t e c t e d i n t s i z e ;
// methods o f Chain come he r e}
70 / 79
Images/cinvestav-1.jpg
Example of add(index) at the end
ProcessCheck if (index==size-1)
NextMake the lastNode.next = TempNode
ThenTempNode.next = firstNode
71 / 79
Images/cinvestav-1.jpg
Example of add(index) at the end
ProcessCheck if (index==size-1)
NextMake the lastNode.next = TempNode
ThenTempNode.next = firstNode
71 / 79
Images/cinvestav-1.jpg
Example of add(index) at the end
ProcessCheck if (index==size-1)
NextMake the lastNode.next = TempNode
ThenTempNode.next = firstNode
71 / 79
Images/cinvestav-1.jpg
Circular List
Add at the end
CA EDB
firstNode lastNode
F
lastNode.next = TempNode
TempNode
73 / 79
Images/cinvestav-1.jpg
Circular List
Add at the end
CA EDB
firstNode
lastNode
F
TempNode.next = firstNode TempNode
74 / 79
Images/cinvestav-1.jpg
We have other representations for the lists
Doubly Linked ListYou have two chain list going through the nodes.It has a firstNodeIt has a lastNode
Doubly Linked Circular ListYou have two chain list going through the nodes.It has a firstNode
76 / 79
Images/cinvestav-1.jpg
We have other representations for the lists
Doubly Linked ListYou have two chain list going through the nodes.It has a firstNodeIt has a lastNode
Doubly Linked Circular ListYou have two chain list going through the nodes.It has a firstNode
76 / 79
Images/cinvestav-1.jpg
Doubly Linked List
Doubly Linked List
CA EDB
firstNode lastNode
NULL
NULL
What about the changes here
77 / 79
Images/cinvestav-1.jpg
Doubly Linked Circular List
Doubly Linked Circular List
CA EDB
firstNode
78 / 79
Images/cinvestav-1.jpg
Where does Java has all these things?
Packagejava.util.LinkedList
There you haveIt has the Linked implementation of a linear list.It has the doubly linked circular list with header node.It Has all methods of LinearList plus many more.
79 / 79
Images/cinvestav-1.jpg
Where does Java has all these things?
Packagejava.util.LinkedList
There you haveIt has the Linked implementation of a linear list.It has the doubly linked circular list with header node.It Has all methods of LinearList plus many more.
79 / 79