SlideShare une entreprise Scribd logo
1  sur  140
Télécharger pour lire hors ligne
Data Structures
Iterators and Chain Linear List
Andres Mendez-Vazquez
May 6, 2015
1 / 79
Images/cinvestav-
Outline
1 Iterators
Interface
Separate and Inner Class Iterator
2 Introduction
Linked Representation
Memory Layout
3 Operations
IsEmpty()
size()
Get(Index)
Remove
Add
4 Can we simplify the code?
5 Other data structures based in the Linked List
2 / 79
Images/cinvestav-
Iterator Method
Scenario
We often want to access every item in a data structure or collection in
turn...
Example with the array representation
1 int listSize = SomeList.size();
2 for (int i = 0; i < listSize; i++)
3 System.out.println(SomeList.get(i));
3 / 79
Images/cinvestav-
Iterator Method
Scenario
We often want to access every item in a data structure or collection in
turn...
Example with the array representation
1 int listSize = SomeList.size();
2 for (int i = 0; i < listSize; i++)
3 System.out.println(SomeList.get(i));
3 / 79
Images/cinvestav-
Motivation
Question
What if we have a get that is really complex?
For example the get in a Chain List
We will see that it has complexity O(n)!!!
Previous Code
What a waste of time!!! O n2 !!!!
4 / 79
Images/cinvestav-
Motivation
Question
What if we have a get that is really complex?
For example the get in a Chain List
We will see that it has complexity O(n)!!!
Previous Code
What a waste of time!!! O n2 !!!!
4 / 79
Images/cinvestav-
Motivation
Question
What if we have a get that is really complex?
For example the get in a Chain List
We will see that it has complexity O(n)!!!
Previous Code
What a waste of time!!! O n2 !!!!
4 / 79
Images/cinvestav-
Then
Something Notable
Iteration is such a common operation that we could include it as part of
the ADT list.
However
We do not want to add another operation to the ADT each time we think
of another way to use an iteration.
5 / 79
Images/cinvestav-
Then
Something Notable
Iteration is such a common operation that we could include it as part of
the ADT list.
However
We do not want to add another operation to the ADT each time we think
of another way to use an iteration.
5 / 79
Images/cinvestav-
Outline
1 Iterators
Interface
Separate and Inner Class Iterator
2 Introduction
Linked Representation
Memory Layout
3 Operations
IsEmpty()
size()
Get(Index)
Remove
Add
4 Can we simplify the code?
5 Other data structures based in the Linked List
6 / 79
Images/cinvestav-
In Java at java.util we have the interface Iterator
Interface
package java . 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 boolean hasNext ( ) ;
p u b l i c Item next ( ) ;
// Optional method
p u b l i c void remove ( ) ;
} // end I t e r a t o r
7 / 79
Images/cinvestav-
Explanation
public boolean hasNext()
It detects whether this iterator has completed its traversal and gone
beyond 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 iterator
by one position.
It returns a reference to the next entry in the iteration, if one exists
It throws NoSuchElementException if the iterator had reached the
end already, that is, if hasNext() is false.
8 / 79
Images/cinvestav-
Explanation
public boolean hasNext()
It detects whether this iterator has completed its traversal and gone
beyond 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 iterator
by one position.
It returns a reference to the next entry in the iteration, if one exists
It throws NoSuchElementException if the iterator had reached the
end already, that is, if hasNext() is false.
8 / 79
Images/cinvestav-
Explanation
public boolean hasNext()
It detects whether this iterator has completed its traversal and gone
beyond 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 iterator
by one position.
It returns a reference to the next entry in the iteration, if one exists
It throws NoSuchElementException if the iterator had reached the
end already, that is, if hasNext() is false.
8 / 79
Images/cinvestav-
Explanation
public boolean hasNext()
It detects whether this iterator has completed its traversal and gone
beyond 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 iterator
by one position.
It returns a reference to the next entry in the iteration, if one exists
It throws NoSuchElementException if the iterator had reached the
end already, that is, if hasNext() is false.
8 / 79
Images/cinvestav-
Explanation
public boolean hasNext()
It detects whether this iterator has completed its traversal and gone
beyond 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 iterator
by one position.
It returns a reference to the next entry in the iteration, if one exists
It throws NoSuchElementException if the iterator had reached the
end already, that is, if hasNext() is false.
8 / 79
Images/cinvestav-
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.
It throws IllegalStateException if next() has not been
called, or if remove() was called already after the last
call to next().
9 / 79
Images/cinvestav-
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.
It throws IllegalStateException if next() has not been
called, or if remove() was called already after the last
call to next().
9 / 79
Images/cinvestav-
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.
It throws IllegalStateException if next() has not been
called, or if remove() was called already after the last
call to next().
9 / 79
Images/cinvestav-
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-
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-
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-
NO FREE LUNCH!!!
Remark
Some details of using an iterator depend on the approach used to
implement the iterator methods.
We can do the following
A possible, but not optimal, way to provide an ADT with traversal
operations is to define them as ADT operations.
For example, if ListInterface extends Iterator, a list object would
have iterator methods as well as list methods.
PROBLEM!!! What if you want to have two or more iterators over the
object list making different things at the same time!!!
11 / 79
Images/cinvestav-
NO FREE LUNCH!!!
Remark
Some details of using an iterator depend on the approach used to
implement the iterator methods.
We can do the following
A possible, but not optimal, way to provide an ADT with traversal
operations is to define them as ADT operations.
For example, if ListInterface extends Iterator, a list object would
have iterator methods as well as list methods.
PROBLEM!!! What if you want to have two or more iterators over the
object list making different things at the same time!!!
11 / 79
Images/cinvestav-
NO FREE LUNCH!!!
Remark
Some details of using an iterator depend on the approach used to
implement the iterator methods.
We can do the following
A possible, but not optimal, way to provide an ADT with traversal
operations is to define them as ADT operations.
For example, if ListInterface extends Iterator, a list object would
have iterator methods as well as list methods.
PROBLEM!!! What if you want to have two or more iterators over the
object list making different things at the same time!!!
11 / 79
Images/cinvestav-
NO FREE LUNCH!!!
Remark
Some details of using an iterator depend on the approach used to
implement the iterator methods.
We can do the following
A possible, but not optimal, way to provide an ADT with traversal
operations is to define them as ADT operations.
For example, if ListInterface extends Iterator, a list object would
have iterator methods as well as list methods.
PROBLEM!!! What if you want to have two or more iterators over the
object list making different things at the same time!!!
11 / 79
Images/cinvestav-
Outline
1 Iterators
Interface
Separate and Inner Class Iterator
2 Introduction
Linked Representation
Memory Layout
3 Operations
IsEmpty()
size()
Get(Index)
Remove
Add
4 Can we simplify the code?
5 Other data structures based in the Linked List
12 / 79
Images/cinvestav-
Solution
We can have
Separate class iterator
Inner Class Iterator
For separate class iterator, we have stuff like this
Iterator<String> nameIterator = new
SeparateIterator<String>(nameList);
13 / 79
Images/cinvestav-
Solution
We can have
Separate class iterator
Inner Class Iterator
For separate class iterator, we have stuff like this
Iterator<String> nameIterator = new
SeparateIterator<String>(nameList);
13 / 79
Images/cinvestav-
Solution
We can have
Separate class iterator
Inner Class Iterator
For separate class iterator, we have stuff like this
Iterator<String> nameIterator = new
SeparateIterator<String>(nameList);
13 / 79
Images/cinvestav-
Example
Problem Number of times Any Name Appears in the list
14 / 79
Images/cinvestav-
Multiple Iterators
Thus
External Iterators provides a solution to multiple iterators
However
Huge Problem
We can only access the list through the public methods:
What if they are not enough?
15 / 79
Images/cinvestav-
Multiple Iterators
Thus
External Iterators provides a solution to multiple iterators
However
Object Iterator from
separate class
iterators
Object from class list
list
Lou
Peg
Meg
ME
Iterator
Cursor
Next
Position2
Huge Problem
We can only access the list through the public methods:
What if they are not enough?
15 / 79
Images/cinvestav-
Separate Iterator Code
Code
import java . u t i l . I t e r a t o r ;
import java . u t i l . NoSuchElementException ;
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 of entry l a s t r et urn ed 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 remove
p r i v a t e boolean wasNextCalled ;
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> a L i s t ) {
// A l l that i t i m p l i e s
} // end c o n s t r u c t o r
< Implementations of the methods hasNext , . . .
next , and remove go here > . . .
} // end S e p a r a t e I t e r a t o r
16 / 79
Images/cinvestav-
We need a better solution!!!
Declare a inner class
So you can have direct access to the protected or private elements in the
object!!!
Actually you have something like this
17 / 79
Images/cinvestav-
We need a better solution!!!
Declare a inner class
So you can have direct access to the protected or private elements in the
object!!!
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-
Inner Class Code
Code
import j a v a . u t i l . I t e r a t o r ;
import j a v a . u t i l . NoSuchElementException ;
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 t
implements I t e r a t o r <T> {
p r i v a t e i n t nextIndex ;
p r i v a t e boolean wasNextCalled ;
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 () {
nextIndex = 0;
wasNextCalled = f a l s e ;
} // end d e f a u l t c o n s t r u c t o r
< Implementations of the methods i n the
i n t e r f a c e I t e r a t o r go here > . . . }
// 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-
So, we have...
Advantages
It is a way of logically grouping classes that are only used in one place.
It increases encapsulation
It can lead to more readable and maintainable code.
Example
ArrayListWithIterator<Integers> SOME = new
ArrayListWithIterator<Integers>();
ArrayListWithIterator.IteratorForArrayList fl = SOME. new
IteratorForArrayList();
19 / 79
Images/cinvestav-
So, we have...
Advantages
It is a way of logically grouping classes that are only used in one place.
It increases encapsulation
It can lead to more readable and maintainable code.
Example
ArrayListWithIterator<Integers> SOME = new
ArrayListWithIterator<Integers>();
ArrayListWithIterator.IteratorForArrayList fl = SOME. new
IteratorForArrayList();
19 / 79
Images/cinvestav-
So, we have...
Advantages
It is a way of logically grouping classes that are only used in one place.
It increases encapsulation
It can lead to more readable and maintainable code.
Example
ArrayListWithIterator<Integers> SOME = new
ArrayListWithIterator<Integers>();
ArrayListWithIterator.IteratorForArrayList fl = SOME. new
IteratorForArrayList();
19 / 79
Images/cinvestav-
So, we have...
Advantages
It is a way of logically grouping classes that are only used in one place.
It increases encapsulation
It can lead to more readable and maintainable code.
Example
ArrayListWithIterator<Integers> SOME = new
ArrayListWithIterator<Integers>();
ArrayListWithIterator.IteratorForArrayList fl = SOME. new
IteratorForArrayList();
19 / 79
Images/cinvestav-
Outline
1 Iterators
Interface
Separate and Inner Class Iterator
2 Introduction
Linked Representation
Memory Layout
3 Operations
IsEmpty()
size()
Get(Index)
Remove
Add
4 Can we simplify the code?
5 Other data structures based in the Linked List
20 / 79
Images/cinvestav-
Linked Representation
Storage
List elements are stored, in memory, in an arbitrary order.
How you move through it
Explicit information (called a link) is used to go from one element to the
next.
21 / 79
Images/cinvestav-
Linked Representation
Storage
List elements are stored, in memory, in an arbitrary order.
How you move through it
Explicit information (called a link) is used to go from one element to the
next.
21 / 79
Images/cinvestav-
Outline
1 Iterators
Interface
Separate and Inner Class Iterator
2 Introduction
Linked Representation
Memory Layout
3 Operations
IsEmpty()
size()
Get(Index)
Remove
Add
4 Can we simplify the code?
5 Other data structures based in the Linked List
22 / 79
Images/cinvestav-
Memory Layout
We have the following
C A E D B
firstNode
First
Last pointer (or link) from E is null
Thus
You can use a variable firstNode to get to the first element in the Linked
List.
23 / 79
Images/cinvestav-
Memory Layout
We have the following
C A E D B
firstNode
First
Last pointer (or link) from E is null
Thus
You can use a variable firstNode to get to the first element in the Linked
List.
23 / 79
Images/cinvestav-
Memory Layout
We have the following
C A E D B
firstNode
First
Last pointer (or link) from E is null
Thus
You can use a variable firstNode to get to the first element in the Linked
List.
23 / 79
Images/cinvestav-
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-
Actually, we know this as a Chain
First
A chain is a linked list in which each node represents one element.
Second
There is a link or pointer from one element to the next.
Third
The last node has a null pointer.
25 / 79
Images/cinvestav-
Actually, we know this as a Chain
First
A chain is a linked list in which each node represents one element.
Second
There is a link or pointer from one element to the next.
Third
The last node has a null pointer.
25 / 79
Images/cinvestav-
Actually, we know this as a Chain
First
A chain is a linked list in which each node represents one element.
Second
There is a link or pointer from one element to the next.
Third
The last node has a null pointer.
25 / 79
Images/cinvestav-
Code for ChainNode
Code
package L i n e a r L i s t ;
// Using Generic in Java
c l a s s ChainNode<Item>{
// package data members
protected Item element ;
protected ChainNode next ;
// c o n s t r u c t o r s and methods come here
}
26 / 79
Images/cinvestav-
The Constructors for ChainNode
A classic one
package L i n e a r L i s t ;
// Using Generic in Java
p u b l i c ChainNode (){
// Set the next node
t h i s . element = n u l l ;
t h i s . next = n u l l ;
}
p u b l i c ChainNode ( Item elem ){
// Set element
t h i s . element = elem ;
t h i s . next = n u l l ;
}
27 / 79
Images/cinvestav-
What about the Class Chain?
Code
/∗∗ l i n k e d implementation of 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 ;
import java . u t i l . ∗ ; // has I t e r a t o r
p 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 members
protected ChainNode<Item> f i r s t N o d e ;
protected i n t s i z e ;
// methods of Chain come here
}
28 / 79
Images/cinvestav-
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 of f i r s t N o d e and s i z e
// are n u l l and 0 , r e s p e c t i v e l y
}
A simple example
public Chain<Item> ()
{
this.firstNode = new ChainNode<Item>();
this.size = 0;
}
29 / 79
Images/cinvestav-
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 of f i r s t N o d e and s i z e
// are n u l l and 0 , r e s p e c t i v e l y
}
A simple example
public Chain<Item> ()
{
this.firstNode = new ChainNode<Item>();
this.size = 0;
}
29 / 79
Images/cinvestav-
Outline
1 Iterators
Interface
Separate and Inner Class Iterator
2 Introduction
Linked Representation
Memory Layout
3 Operations
IsEmpty()
size()
Get(Index)
Remove
Add
4 Can we simplify the code?
5 Other data structures based in the Linked List
30 / 79
Images/cinvestav-
IsEmpty()
Really Simple Code
/∗∗ @return true i f f l i s t i s empty ∗/
p u b l i c boolean isEmpty ()
{ r e t u r n s i z e == 0;}
31 / 79
Images/cinvestav-
Outline
1 Iterators
Interface
Separate and Inner Class Iterator
2 Introduction
Linked Representation
Memory Layout
3 Operations
IsEmpty()
size()
Get(Index)
Remove
Add
4 Can we simplify the code?
5 Other data structures based in the Linked List
32 / 79
Images/cinvestav-
size()
Really Simple Code
/∗∗ @return c u r r e n t number of elements in 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-
Outline
1 Iterators
Interface
Separate and Inner Class Iterator
2 Introduction
Linked Representation
Memory Layout
3 Operations
IsEmpty()
size()
Get(Index)
Remove
Add
4 Can we simplify the code?
5 Other data structures based in the Linked List
34 / 79
Images/cinvestav-
Operations: Get
Example
CA EDB
firstNode
Link or pointer field of node
Data field of node
NULL
What to do to implement Get
1 Check Index
2 Move to the correct position
For example: TempNode = firstNode.next.next.next.
You actually use a loop.
3 return TempNode.element
35 / 79
Images/cinvestav-
Operations: Get
Example
CA EDB
firstNode
Link or pointer field of node
Data field of node
NULL
What to do to implement Get
1 Check Index
2 Move to the correct position
For example: TempNode = firstNode.next.next.next.
You actually use a loop.
3 return TempNode.element
35 / 79
Images/cinvestav-
Process
Check Index
0 ≤ index ≤ size − 1 (1)
Negate the statement to use it
How?
36 / 79
Images/cinvestav-
Process
Check Index
0 ≤ index ≤ size − 1 (1)
Negate the statement to use it
How?
36 / 79
Images/cinvestav-
Move to the correct place
How?
CA EDB
firstNode NULL
TempNode=firstNode
37 / 79
Images/cinvestav-
Move to the correct place
Index == 2
CA EDB
firstNode NULL
TempNode=firstNode
index==2
38 / 79
Images/cinvestav-
Move to the correct place
Index == 2
CA EDB
firstNode NULL
TempNode=TempNode.next
index==2
39 / 79
Images/cinvestav-
Move to the correct place
Index == 2
CA EDB
firstNode NULL
TempNode=TempNode.next
index==2
40 / 79
Images/cinvestav-
Move to the correct place
Index == 2
CA EDB
firstNode NULL
return TempNode.element
index==2
41 / 79
Images/cinvestav-
Code
Here is the method
p u b l i c <Item> get ( i n t index ){
ChainNode<Item> TempNode ;
//Check always
i 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 ( " Index ␣ out ␣ of ␣bound " ) ;
System . e x i t ( 0 ) ;
}
//Move to the c o r r e c t p o s i t i o n
TempNode = t h i s . f i r s t N o d e ;
f o r ( i n t i =0 ; i <index ; i ++){
TempNode = TempNode . next ;
}
r e t u r n TempNode . element ;
}
42 / 79
Images/cinvestav-
Outline
1 Iterators
Interface
Separate and Inner Class Iterator
2 Introduction
Linked Representation
Memory Layout
3 Operations
IsEmpty()
size()
Get(Index)
Remove
Add
4 Can we simplify the code?
5 Other data structures based in the Linked List
43 / 79
Images/cinvestav-
Now, Remove
We have two cases
Any ideas?
Case I
Removing from the beginning.
Case II
Remove from the middle.
44 / 79
Images/cinvestav-
Now, Remove
We have two cases
Any ideas?
Case I
Removing from the beginning.
Case II
Remove from the middle.
44 / 79
Images/cinvestav-
Now, Remove
We have two cases
Any ideas?
Case I
Removing from the beginning.
Case II
Remove from the middle.
44 / 79
Images/cinvestav-
Case I: Remove(0)
Process
1 if index == 0 do
1 TempNode = firstNode
2 firstNode=firstNode.next
3 TempNode.next=NULL
4 return TempNode.element
45 / 79
Images/cinvestav-
Case I: Remove(0)
Process
1 if index == 0 do
1 TempNode = firstNode
2 firstNode=firstNode.next
3 TempNode.next=NULL
4 return TempNode.element
45 / 79
Images/cinvestav-
Case I: Remove(0)
Process
1 if index == 0 do
1 TempNode = firstNode
2 firstNode=firstNode.next
3 TempNode.next=NULL
4 return TempNode.element
45 / 79
Images/cinvestav-
Case I: Remove(0)
Process
1 if index == 0 do
1 TempNode = firstNode
2 firstNode=firstNode.next
3 TempNode.next=NULL
4 return TempNode.element
45 / 79
Images/cinvestav-
Case I: Remove(0)
Process
1 if index == 0 do
1 TempNode = firstNode
2 firstNode=firstNode.next
3 TempNode.next=NULL
4 return TempNode.element
45 / 79
Images/cinvestav-
Process
TempNode=firstNode
CA EDB
firstNode NULL
TempNode=firstNode
46 / 79
Images/cinvestav-
Process
firstNode=firstNode.next
CA EDB
firstNode NULL
TempNode
47 / 79
Images/cinvestav-
Process
TempNode.next=NULL
CA EDB
firstNode NULL
TempNode NULL
48 / 79
Images/cinvestav-
Process
return TempNode.element
CA EDB
firstNode NULL
return TempNode.element
NULL
49 / 79
Images/cinvestav-
Case II: Remove(2)
Process
1 Check Index
2 Starting at the first node
3 TempNode=firstNode;
4 Loop doing
1 beforeNode=TempNode;
2 TempNode=TempNode.next;
5 before.next = TempNode.next
6 TempNode.next = NULL
7 return TempNode.element
50 / 79
Images/cinvestav-
Case II: Remove(2)
Process
1 Check Index
2 Starting at the first node
3 TempNode=firstNode;
4 Loop doing
1 beforeNode=TempNode;
2 TempNode=TempNode.next;
5 before.next = TempNode.next
6 TempNode.next = NULL
7 return TempNode.element
50 / 79
Images/cinvestav-
Case II: Remove(2)
Process
1 Check Index
2 Starting at the first node
3 TempNode=firstNode;
4 Loop doing
1 beforeNode=TempNode;
2 TempNode=TempNode.next;
5 before.next = TempNode.next
6 TempNode.next = NULL
7 return TempNode.element
50 / 79
Images/cinvestav-
Case II: Remove(2)
Process
1 Check Index
2 Starting at the first node
3 TempNode=firstNode;
4 Loop doing
1 beforeNode=TempNode;
2 TempNode=TempNode.next;
5 before.next = TempNode.next
6 TempNode.next = NULL
7 return TempNode.element
50 / 79
Images/cinvestav-
Case II: Remove(2)
Process
1 Check Index
2 Starting at the first node
3 TempNode=firstNode;
4 Loop doing
1 beforeNode=TempNode;
2 TempNode=TempNode.next;
5 before.next = TempNode.next
6 TempNode.next = NULL
7 return TempNode.element
50 / 79
Images/cinvestav-
Case II: Remove(2)
Process
1 Check Index
2 Starting at the first node
3 TempNode=firstNode;
4 Loop doing
1 beforeNode=TempNode;
2 TempNode=TempNode.next;
5 before.next = TempNode.next
6 TempNode.next = NULL
7 return TempNode.element
50 / 79
Images/cinvestav-
Case II: Remove(2)
Process
1 Check Index
2 Starting at the first node
3 TempNode=firstNode;
4 Loop doing
1 beforeNode=TempNode;
2 TempNode=TempNode.next;
5 before.next = TempNode.next
6 TempNode.next = NULL
7 return TempNode.element
50 / 79
Images/cinvestav-
Case II: Remove(2)
Process
1 Check Index
2 Starting at the first node
3 TempNode=firstNode;
4 Loop doing
1 beforeNode=TempNode;
2 TempNode=TempNode.next;
5 before.next = TempNode.next
6 TempNode.next = NULL
7 return TempNode.element
50 / 79
Images/cinvestav-
Case II: Remove(2)
Process
1 Check Index
2 Starting at the first node
3 TempNode=firstNode;
4 Loop doing
1 beforeNode=TempNode;
2 TempNode=TempNode.next;
5 before.next = TempNode.next
6 TempNode.next = NULL
7 return TempNode.element
50 / 79
Images/cinvestav-
Process
TempNode=firstNode
CA EDB
firstNode NULL
TempNode=firstNode
51 / 79
Images/cinvestav-
Process: index == 2
beforeNode=TempNode;
TempNode=TempNode.next;
CA EDB
firstNode NULL
beforeNode=TempNode TempNode=TempNode.next
index==2
52 / 79
Images/cinvestav-
Process: index == 2
beforeNode=TempNode;
TempNode=TempNode.next;
CA EDB
firstNode NULL
beforeNode=TempNode TempNode=TempNode.next
index==2
53 / 79
Images/cinvestav-
Process: index == 2
before.next = TempNode.next
CA EDB
firstNode NULL
beforeNode.next=TempNode.next
54 / 79
Images/cinvestav-
Process: index == 2
TempNode.next = NULL
CA EDB
firstNode NULL
TempNode=TempNode.next
NULL
55 / 79
Images/cinvestav-
Process: index == 2
TempNode.next = NULL
CA EDB
firstNode NULL
return TempNode.element
NULL
56 / 79
Images/cinvestav-
Outline
1 Iterators
Interface
Separate and Inner Class Iterator
2 Introduction
Linked Representation
Memory Layout
3 Operations
IsEmpty()
size()
Get(Index)
Remove
Add
4 Can we simplify the code?
5 Other data structures based in the Linked List
57 / 79
Images/cinvestav-
Now, Add
We have four cases
Any ideas?
Case I
The Chain is Empty
Case II
Add at the beginning.
58 / 79
Images/cinvestav-
Now, Add
We have four cases
Any ideas?
Case I
The Chain is Empty
Case II
Add at the beginning.
58 / 79
Images/cinvestav-
Now, Add
We have four cases
Any ideas?
Case I
The Chain is Empty
Case II
Add at the beginning.
58 / 79
Images/cinvestav-
Now, Add
We have four cases
Any ideas?
Case III
Add at the middle.
Case IV
Add at the end.
59 / 79
Images/cinvestav-
Now, Add
We have four cases
Any ideas?
Case III
Add at the middle.
Case IV
Add at the end.
59 / 79
Images/cinvestav-
Now, Add
We have four cases
Any ideas?
Case III
Add at the middle.
Case IV
Add at the end.
59 / 79
Images/cinvestav-
Why?
Think About it!!!
Remember you have a sequential access.
60 / 79
Images/cinvestav-
Add at an empty list
Steps
1 Create a node to store the element, NewNode
2 Then assign firstNode = NewNode
61 / 79
Images/cinvestav-
Add at an empty list
Steps
1 Create a node to store the element, NewNode
2 Then assign firstNode = NewNode
61 / 79
Images/cinvestav-
Add at an empty list
Steps
1 Create a node to store the element, NewNode
2 Then assign firstNode = NewNode
firstNode
K
NULL
61 / 79
Images/cinvestav-
Add At the Beginning
Steps
1 Create a node to store the element, NewNode
2 Do NewNode.next = firstNode
3 Then reassign firstNode = NewNode
4 Then, size = size +1
62 / 79
Images/cinvestav-
Add At the Beginning
Steps
1 Create a node to store the element, NewNode
2 Do NewNode.next = firstNode
3 Then reassign firstNode = NewNode
4 Then, size = size +1
62 / 79
Images/cinvestav-
Add At the Beginning
Steps
1 Create a node to store the element, NewNode
2 Do NewNode.next = firstNode
3 Then reassign firstNode = NewNode
4 Then, size = size +1
62 / 79
Images/cinvestav-
Add At the Beginning
Steps
1 Create a node to store the element, NewNode
2 Do NewNode.next = firstNode
3 Then reassign firstNode = NewNode
4 Then, size = size +1
62 / 79
Images/cinvestav-
Add At the Beginning
Steps
1 Create a node to store the element, NewNode
2 Do NewNode.next = firstNode
3 Then reassign firstNode = NewNode
4 Then, size = size +1
CA EDB
firstNode
NULL
K
62 / 79
Images/cinvestav-
What about the other case?
Do you have an idea?
Add at the Middle.
Add at the end.
63 / 79
Images/cinvestav-
What about the other methods?
Linear List
AbstractDataType LinearList
{
instances
ordered finite collections of zero or more elements
operations
isEmpty(): return true iff the list is empty, false otherwise
size(): return the list size (i.e., number of elements in the list)
get(index): return the element with the “index” index
indexOf(x): return the index of the first occurrence of x in the list, return -1
if x is not in the list
remove(index): remove and return the indexth element, elements with higher
index have their index reduced by 1
add(theIndex, x): insert x as the index of th element, elements with
theIndex ≥ index have their index increased by 1
output(): output the list elements from left to right
}
64 / 79
Images/cinvestav-
Complexity of Linked List
We have
Dynamic Array Linked List
Amortized Analysis
Indexing 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-
Average Performance with Each Implementation on a Slow
Machine!!!
40,000 Operations each type on a 350Mhz PC
Operation FastArrayLinearList Chain
average get 5.6 ms 157 sec
average adds 5.8 sec 115 sec
average removes 5.8 sec 157 sec
66 / 79
Images/cinvestav-
Can we simplify the code?
How?
We would like to simplify the code.... How?
What about
67 / 79
Images/cinvestav-
Can we simplify the code?
How?
We would like to simplify the code.... How?
What about
CA EDB
headerNode NULL
67 / 79
Images/cinvestav-
Can we simplify the code?
Then, the empty list looks like
headerNode
Thus
This simplify a lot the code because everything is a middle node
68 / 79
Images/cinvestav-
Can we simplify the code?
Then, the empty list looks like
headerNode
Thus
This simplify a lot the code because everything is a middle node
68 / 79
Images/cinvestav-
Circular List
Circular List
CA EDB
firstNode lastNode
69 / 79
Images/cinvestav-
Here, we need to have the following changes
We need to add the following to the class
/∗∗ l i n k e d implementation of 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 ;
import java . u t i l . ∗ ; // has I t e r a t o r
p 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 members
protected ChainNode<Item> f i r s t N o d e ;
protected ChainNode<Item> lastNode ;
protected i n t s i z e ;
// methods of Chain come here
}
70 / 79
Images/cinvestav-
Example of add(index) at the end
Process
Check if (index==size-1)
Next
Make the lastNode.next = TempNode
Then
TempNode.next = firstNode
71 / 79
Images/cinvestav-
Example of add(index) at the end
Process
Check if (index==size-1)
Next
Make the lastNode.next = TempNode
Then
TempNode.next = firstNode
71 / 79
Images/cinvestav-
Example of add(index) at the end
Process
Check if (index==size-1)
Next
Make the lastNode.next = TempNode
Then
TempNode.next = firstNode
71 / 79
Images/cinvestav-
Example of add(index) at the end
Finally
lastNode = TempNode
72 / 79
Images/cinvestav-
Circular List
Add at the end
CA EDB
firstNode lastNode
F
lastNode.next = TempNode
TempNode
73 / 79
Images/cinvestav-
Circular List
Add at the end
CA EDB
firstNode
lastNode
F
TempNode.next = firstNode TempNode
74 / 79
Images/cinvestav-
Circular List
Add at the end
CA EDB
firstNode
F
lastNode=TempNode
75 / 79
Images/cinvestav-
We have other representations for the lists
Doubly Linked List
You have two chain list going through the nodes.
It has a firstNode
It has a lastNode
Doubly Linked Circular List
You have two chain list going through the nodes.
It has a firstNode
76 / 79
Images/cinvestav-
We have other representations for the lists
Doubly Linked List
You have two chain list going through the nodes.
It has a firstNode
It has a lastNode
Doubly Linked Circular List
You have two chain list going through the nodes.
It has a firstNode
76 / 79
Images/cinvestav-
Doubly Linked List
Doubly Linked List
CA EDB
firstNode lastNode
NULL
NULL
What about the changes here
77 / 79
Images/cinvestav-
Doubly Linked Circular List
Doubly Linked Circular List
CA EDB
firstNode
78 / 79
Images/cinvestav-
Where does Java has all these things?
Package
java.util.LinkedList
There you have
It 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-
Where does Java has all these things?
Package
java.util.LinkedList
There you have
It 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-
Where does Java has all these things?
Package
java.util.LinkedList
There you have
It 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

Contenu connexe

Tendances

Tendances (19)

Queues
QueuesQueues
Queues
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
 
Heaps & priority queues
Heaps & priority queuesHeaps & priority queues
Heaps & priority queues
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java Generics
 
Presentation on queue
Presentation on queuePresentation on queue
Presentation on queue
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
7array in c#
7array in c#7array in c#
7array in c#
 
Python Modules, Packages and Libraries
Python Modules, Packages and LibrariesPython Modules, Packages and Libraries
Python Modules, Packages and Libraries
 
Array and Collections in c#
Array and Collections in c#Array and Collections in c#
Array and Collections in c#
 
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCEFUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Chapter03
Chapter03Chapter03
Chapter03
 
2 introduction to data structure
2  introduction to data structure2  introduction to data structure
2 introduction to data structure
 
C++ STL 概觀
C++ STL 概觀C++ STL 概觀
C++ STL 概觀
 
Whiteboarding Coding Challenges in Python
Whiteboarding Coding Challenges in PythonWhiteboarding Coding Challenges in Python
Whiteboarding Coding Challenges in Python
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 

En vedette

Work energy power 2 reading assignment -revision 2
Work energy power 2 reading assignment -revision 2Work energy power 2 reading assignment -revision 2
Work energy power 2 reading assignment -revision 2
sashrilisdi
 
Periodic table (1)
Periodic table (1)Periodic table (1)
Periodic table (1)
jghopwood
 

En vedette (20)

07 Machine Learning - Expectation Maximization
07 Machine Learning - Expectation Maximization07 Machine Learning - Expectation Maximization
07 Machine Learning - Expectation Maximization
 
Work energy power 2 reading assignment -revision 2
Work energy power 2 reading assignment -revision 2Work energy power 2 reading assignment -revision 2
Work energy power 2 reading assignment -revision 2
 
Periodic table (1)
Periodic table (1)Periodic table (1)
Periodic table (1)
 
11 Machine Learning Important Issues in Machine Learning
11 Machine Learning Important Issues in Machine Learning11 Machine Learning Important Issues in Machine Learning
11 Machine Learning Important Issues in Machine Learning
 
Preparation Data Structures 10 trees
Preparation Data Structures 10 treesPreparation Data Structures 10 trees
Preparation Data Structures 10 trees
 
01 Machine Learning Introduction
01 Machine Learning Introduction 01 Machine Learning Introduction
01 Machine Learning Introduction
 
23 Matrix Algorithms
23 Matrix Algorithms23 Matrix Algorithms
23 Matrix Algorithms
 
Drainage
DrainageDrainage
Drainage
 
What's the Matter?
What's the Matter?What's the Matter?
What's the Matter?
 
03 Probability Review for Analysis of Algorithms
03 Probability Review for Analysis of Algorithms03 Probability Review for Analysis of Algorithms
03 Probability Review for Analysis of Algorithms
 
13 Machine Learning Supervised Decision Trees
13 Machine Learning Supervised Decision Trees13 Machine Learning Supervised Decision Trees
13 Machine Learning Supervised Decision Trees
 
Waves
WavesWaves
Waves
 
26 Computational Geometry
26 Computational Geometry26 Computational Geometry
26 Computational Geometry
 
Preparation Data Structures 11 graphs
Preparation Data Structures 11 graphsPreparation Data Structures 11 graphs
Preparation Data Structures 11 graphs
 
31 Machine Learning Unsupervised Cluster Validity
31 Machine Learning Unsupervised Cluster Validity31 Machine Learning Unsupervised Cluster Validity
31 Machine Learning Unsupervised Cluster Validity
 
15 B-Trees
15 B-Trees15 B-Trees
15 B-Trees
 
Force resolution force
Force resolution forceForce resolution force
Force resolution force
 
F1
F1F1
F1
 
Force resultant force
Force resultant forceForce resultant force
Force resultant force
 
23 Machine Learning Feature Generation
23 Machine Learning Feature Generation23 Machine Learning Feature Generation
23 Machine Learning Feature Generation
 

Similaire à Preparation Data Structures 05 chain linear_list

computer notes - Data Structures - 5
computer notes - Data Structures - 5computer notes - Data Structures - 5
computer notes - Data Structures - 5
ecomputernotes
 
Array with Iterator. Java styleImplement an array data structure a.pdf
Array with Iterator. Java styleImplement an array data structure a.pdfArray with Iterator. Java styleImplement an array data structure a.pdf
Array with Iterator. Java styleImplement an array data structure a.pdf
fcaindore
 
Introduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdfIntroduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdf
arpitaeron555
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
karymadelaneyrenne19
 

Similaire à Preparation Data Structures 05 chain linear_list (20)

computer notes - Data Structures - 5
computer notes - Data Structures - 5computer notes - Data Structures - 5
computer notes - Data Structures - 5
 
Computer notes - Josephus Problem
Computer notes - Josephus ProblemComputer notes - Josephus Problem
Computer notes - Josephus Problem
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
 
Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018
 
Lazy java
Lazy javaLazy java
Lazy java
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
 
Array with Iterator. Java styleImplement an array data structure a.pdf
Array with Iterator. Java styleImplement an array data structure a.pdfArray with Iterator. Java styleImplement an array data structure a.pdf
Array with Iterator. Java styleImplement an array data structure a.pdf
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
Collections
CollectionsCollections
Collections
 
The Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidThe Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on Android
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
Introduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdfIntroduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdf
 
A04
A04A04
A04
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
Linked list (java platform se 8 )
Linked list (java platform se 8 )Linked list (java platform se 8 )
Linked list (java platform se 8 )
 
Spl to the Rescue - Zendcon 09
Spl to the Rescue - Zendcon 09Spl to the Rescue - Zendcon 09
Spl to the Rescue - Zendcon 09
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
 

Plus de Andres Mendez-Vazquez

Introduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabusIntroduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabus
Andres Mendez-Vazquez
 

Plus de Andres Mendez-Vazquez (20)

2.03 bayesian estimation
2.03 bayesian estimation2.03 bayesian estimation
2.03 bayesian estimation
 
05 linear transformations
05 linear transformations05 linear transformations
05 linear transformations
 
01.04 orthonormal basis_eigen_vectors
01.04 orthonormal basis_eigen_vectors01.04 orthonormal basis_eigen_vectors
01.04 orthonormal basis_eigen_vectors
 
01.03 squared matrices_and_other_issues
01.03 squared matrices_and_other_issues01.03 squared matrices_and_other_issues
01.03 squared matrices_and_other_issues
 
01.02 linear equations
01.02 linear equations01.02 linear equations
01.02 linear equations
 
01.01 vector spaces
01.01 vector spaces01.01 vector spaces
01.01 vector spaces
 
06 recurrent neural_networks
06 recurrent neural_networks06 recurrent neural_networks
06 recurrent neural_networks
 
05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiation05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiation
 
Zetta global
Zetta globalZetta global
Zetta global
 
01 Introduction to Neural Networks and Deep Learning
01 Introduction to Neural Networks and Deep Learning01 Introduction to Neural Networks and Deep Learning
01 Introduction to Neural Networks and Deep Learning
 
25 introduction reinforcement_learning
25 introduction reinforcement_learning25 introduction reinforcement_learning
25 introduction reinforcement_learning
 
Neural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning SyllabusNeural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning Syllabus
 
Introduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabusIntroduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabus
 
Ideas 09 22_2018
Ideas 09 22_2018Ideas 09 22_2018
Ideas 09 22_2018
 
Ideas about a Bachelor in Machine Learning/Data Sciences
Ideas about a Bachelor in Machine Learning/Data SciencesIdeas about a Bachelor in Machine Learning/Data Sciences
Ideas about a Bachelor in Machine Learning/Data Sciences
 
Analysis of Algorithms Syllabus
Analysis of Algorithms  SyllabusAnalysis of Algorithms  Syllabus
Analysis of Algorithms Syllabus
 
20 k-means, k-center, k-meoids and variations
20 k-means, k-center, k-meoids and variations20 k-means, k-center, k-meoids and variations
20 k-means, k-center, k-meoids and variations
 
18.1 combining models
18.1 combining models18.1 combining models
18.1 combining models
 
17 vapnik chervonenkis dimension
17 vapnik chervonenkis dimension17 vapnik chervonenkis dimension
17 vapnik chervonenkis dimension
 
A basic introduction to learning
A basic introduction to learningA basic introduction to learning
A basic introduction to learning
 

Dernier

Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 

Dernier (20)

SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 

Preparation Data Structures 05 chain linear_list

  • 1. Data Structures Iterators and Chain Linear List Andres Mendez-Vazquez May 6, 2015 1 / 79
  • 2. Images/cinvestav- Outline 1 Iterators Interface Separate and Inner Class Iterator 2 Introduction Linked Representation Memory Layout 3 Operations IsEmpty() size() Get(Index) Remove Add 4 Can we simplify the code? 5 Other data structures based in the Linked List 2 / 79
  • 3. Images/cinvestav- Iterator Method Scenario We often want to access every item in a data structure or collection in turn... Example with the array representation 1 int listSize = SomeList.size(); 2 for (int i = 0; i < listSize; i++) 3 System.out.println(SomeList.get(i)); 3 / 79
  • 4. Images/cinvestav- Iterator Method Scenario We often want to access every item in a data structure or collection in turn... Example with the array representation 1 int listSize = SomeList.size(); 2 for (int i = 0; i < listSize; i++) 3 System.out.println(SomeList.get(i)); 3 / 79
  • 5. Images/cinvestav- Motivation Question What if we have a get that is really complex? For example the get in a Chain List We will see that it has complexity O(n)!!! Previous Code What a waste of time!!! O n2 !!!! 4 / 79
  • 6. Images/cinvestav- Motivation Question What if we have a get that is really complex? For example the get in a Chain List We will see that it has complexity O(n)!!! Previous Code What a waste of time!!! O n2 !!!! 4 / 79
  • 7. Images/cinvestav- Motivation Question What if we have a get that is really complex? For example the get in a Chain List We will see that it has complexity O(n)!!! Previous Code What a waste of time!!! O n2 !!!! 4 / 79
  • 8. Images/cinvestav- Then Something Notable Iteration is such a common operation that we could include it as part of the ADT list. However We do not want to add another operation to the ADT each time we think of another way to use an iteration. 5 / 79
  • 9. Images/cinvestav- Then Something Notable Iteration is such a common operation that we could include it as part of the ADT list. However We do not want to add another operation to the ADT each time we think of another way to use an iteration. 5 / 79
  • 10. Images/cinvestav- Outline 1 Iterators Interface Separate and Inner Class Iterator 2 Introduction Linked Representation Memory Layout 3 Operations IsEmpty() size() Get(Index) Remove Add 4 Can we simplify the code? 5 Other data structures based in the Linked List 6 / 79
  • 11. Images/cinvestav- In Java at java.util we have the interface Iterator Interface package java . 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 boolean hasNext ( ) ; p u b l i c Item next ( ) ; // Optional method p u b l i c void remove ( ) ; } // end I t e r a t o r 7 / 79
  • 12. Images/cinvestav- Explanation public boolean hasNext() It detects whether this iterator has completed its traversal and gone beyond 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 iterator by one position. It returns a reference to the next entry in the iteration, if one exists It throws NoSuchElementException if the iterator had reached the end already, that is, if hasNext() is false. 8 / 79
  • 13. Images/cinvestav- Explanation public boolean hasNext() It detects whether this iterator has completed its traversal and gone beyond 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 iterator by one position. It returns a reference to the next entry in the iteration, if one exists It throws NoSuchElementException if the iterator had reached the end already, that is, if hasNext() is false. 8 / 79
  • 14. Images/cinvestav- Explanation public boolean hasNext() It detects whether this iterator has completed its traversal and gone beyond 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 iterator by one position. It returns a reference to the next entry in the iteration, if one exists It throws NoSuchElementException if the iterator had reached the end already, that is, if hasNext() is false. 8 / 79
  • 15. Images/cinvestav- Explanation public boolean hasNext() It detects whether this iterator has completed its traversal and gone beyond 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 iterator by one position. It returns a reference to the next entry in the iteration, if one exists It throws NoSuchElementException if the iterator had reached the end already, that is, if hasNext() is false. 8 / 79
  • 16. Images/cinvestav- Explanation public boolean hasNext() It detects whether this iterator has completed its traversal and gone beyond 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 iterator by one position. It returns a reference to the next entry in the iteration, if one exists It throws NoSuchElementException if the iterator had reached the end already, that is, if hasNext() is false. 8 / 79
  • 17. Images/cinvestav- 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. It throws IllegalStateException if next() has not been called, or if remove() was called already after the last call to next(). 9 / 79
  • 18. Images/cinvestav- 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. It throws IllegalStateException if next() has not been called, or if remove() was called already after the last call to next(). 9 / 79
  • 19. Images/cinvestav- 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. It throws IllegalStateException if next() has not been called, or if remove() was called already after the last call to next(). 9 / 79
  • 20. Images/cinvestav- 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
  • 21. Images/cinvestav- 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
  • 22. Images/cinvestav- 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
  • 23. Images/cinvestav- NO FREE LUNCH!!! Remark Some details of using an iterator depend on the approach used to implement the iterator methods. We can do the following A possible, but not optimal, way to provide an ADT with traversal operations is to define them as ADT operations. For example, if ListInterface extends Iterator, a list object would have iterator methods as well as list methods. PROBLEM!!! What if you want to have two or more iterators over the object list making different things at the same time!!! 11 / 79
  • 24. Images/cinvestav- NO FREE LUNCH!!! Remark Some details of using an iterator depend on the approach used to implement the iterator methods. We can do the following A possible, but not optimal, way to provide an ADT with traversal operations is to define them as ADT operations. For example, if ListInterface extends Iterator, a list object would have iterator methods as well as list methods. PROBLEM!!! What if you want to have two or more iterators over the object list making different things at the same time!!! 11 / 79
  • 25. Images/cinvestav- NO FREE LUNCH!!! Remark Some details of using an iterator depend on the approach used to implement the iterator methods. We can do the following A possible, but not optimal, way to provide an ADT with traversal operations is to define them as ADT operations. For example, if ListInterface extends Iterator, a list object would have iterator methods as well as list methods. PROBLEM!!! What if you want to have two or more iterators over the object list making different things at the same time!!! 11 / 79
  • 26. Images/cinvestav- NO FREE LUNCH!!! Remark Some details of using an iterator depend on the approach used to implement the iterator methods. We can do the following A possible, but not optimal, way to provide an ADT with traversal operations is to define them as ADT operations. For example, if ListInterface extends Iterator, a list object would have iterator methods as well as list methods. PROBLEM!!! What if you want to have two or more iterators over the object list making different things at the same time!!! 11 / 79
  • 27. Images/cinvestav- Outline 1 Iterators Interface Separate and Inner Class Iterator 2 Introduction Linked Representation Memory Layout 3 Operations IsEmpty() size() Get(Index) Remove Add 4 Can we simplify the code? 5 Other data structures based in the Linked List 12 / 79
  • 28. Images/cinvestav- Solution We can have Separate class iterator Inner Class Iterator For separate class iterator, we have stuff like this Iterator<String> nameIterator = new SeparateIterator<String>(nameList); 13 / 79
  • 29. Images/cinvestav- Solution We can have Separate class iterator Inner Class Iterator For separate class iterator, we have stuff like this Iterator<String> nameIterator = new SeparateIterator<String>(nameList); 13 / 79
  • 30. Images/cinvestav- Solution We can have Separate class iterator Inner Class Iterator For separate class iterator, we have stuff like this Iterator<String> nameIterator = new SeparateIterator<String>(nameList); 13 / 79
  • 31. Images/cinvestav- Example Problem Number of times Any Name Appears in the list 14 / 79
  • 32. Images/cinvestav- Multiple Iterators Thus External Iterators provides a solution to multiple iterators However Huge Problem We can only access the list through the public methods: What if they are not enough? 15 / 79
  • 33. Images/cinvestav- Multiple Iterators Thus External Iterators provides a solution to multiple iterators However Object Iterator from separate class iterators Object from class list list Lou Peg Meg ME Iterator Cursor Next Position2 Huge Problem We can only access the list through the public methods: What if they are not enough? 15 / 79
  • 34. Images/cinvestav- Separate Iterator Code Code import java . u t i l . I t e r a t o r ; import java . u t i l . NoSuchElementException ; 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 of entry l a s t r et urn ed 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 remove p r i v a t e boolean wasNextCalled ; 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> a L i s t ) { // A l l that i t i m p l i e s } // end c o n s t r u c t o r < Implementations of the methods hasNext , . . . next , and remove go here > . . . } // end S e p a r a t e I t e r a t o r 16 / 79
  • 35. Images/cinvestav- We need a better solution!!! Declare a inner class So you can have direct access to the protected or private elements in the object!!! Actually you have something like this 17 / 79
  • 36. Images/cinvestav- We need a better solution!!! Declare a inner class So you can have direct access to the protected or private elements in the object!!! Actually you have something like this Object Iterator from Inner class iterators Object from class array list Lou Peg Meg ME nextPosition2 17 / 79
  • 37. Images/cinvestav- Inner Class Code Code import j a v a . u t i l . I t e r a t o r ; import j a v a . u t i l . NoSuchElementException ; 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 t implements I t e r a t o r <T> { p r i v a t e i n t nextIndex ; p r i v a t e boolean wasNextCalled ; 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 () { nextIndex = 0; wasNextCalled = f a l s e ; } // end d e f a u l t c o n s t r u c t o r < Implementations of the methods i n the i n t e r f a c e I t e r a t o r go here > . . . } // 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
  • 38. Images/cinvestav- So, we have... Advantages It is a way of logically grouping classes that are only used in one place. It increases encapsulation It can lead to more readable and maintainable code. Example ArrayListWithIterator<Integers> SOME = new ArrayListWithIterator<Integers>(); ArrayListWithIterator.IteratorForArrayList fl = SOME. new IteratorForArrayList(); 19 / 79
  • 39. Images/cinvestav- So, we have... Advantages It is a way of logically grouping classes that are only used in one place. It increases encapsulation It can lead to more readable and maintainable code. Example ArrayListWithIterator<Integers> SOME = new ArrayListWithIterator<Integers>(); ArrayListWithIterator.IteratorForArrayList fl = SOME. new IteratorForArrayList(); 19 / 79
  • 40. Images/cinvestav- So, we have... Advantages It is a way of logically grouping classes that are only used in one place. It increases encapsulation It can lead to more readable and maintainable code. Example ArrayListWithIterator<Integers> SOME = new ArrayListWithIterator<Integers>(); ArrayListWithIterator.IteratorForArrayList fl = SOME. new IteratorForArrayList(); 19 / 79
  • 41. Images/cinvestav- So, we have... Advantages It is a way of logically grouping classes that are only used in one place. It increases encapsulation It can lead to more readable and maintainable code. Example ArrayListWithIterator<Integers> SOME = new ArrayListWithIterator<Integers>(); ArrayListWithIterator.IteratorForArrayList fl = SOME. new IteratorForArrayList(); 19 / 79
  • 42. Images/cinvestav- Outline 1 Iterators Interface Separate and Inner Class Iterator 2 Introduction Linked Representation Memory Layout 3 Operations IsEmpty() size() Get(Index) Remove Add 4 Can we simplify the code? 5 Other data structures based in the Linked List 20 / 79
  • 43. Images/cinvestav- Linked Representation Storage List elements are stored, in memory, in an arbitrary order. How you move through it Explicit information (called a link) is used to go from one element to the next. 21 / 79
  • 44. Images/cinvestav- Linked Representation Storage List elements are stored, in memory, in an arbitrary order. How you move through it Explicit information (called a link) is used to go from one element to the next. 21 / 79
  • 45. Images/cinvestav- Outline 1 Iterators Interface Separate and Inner Class Iterator 2 Introduction Linked Representation Memory Layout 3 Operations IsEmpty() size() Get(Index) Remove Add 4 Can we simplify the code? 5 Other data structures based in the Linked List 22 / 79
  • 46. Images/cinvestav- Memory Layout We have the following C A E D B firstNode First Last pointer (or link) from E is null Thus You can use a variable firstNode to get to the first element in the Linked List. 23 / 79
  • 47. Images/cinvestav- Memory Layout We have the following C A E D B firstNode First Last pointer (or link) from E is null Thus You can use a variable firstNode to get to the first element in the Linked List. 23 / 79
  • 48. Images/cinvestav- Memory Layout We have the following C A E D B firstNode First Last pointer (or link) from E is null Thus You can use a variable firstNode to get to the first element in the Linked List. 23 / 79
  • 49. Images/cinvestav- Normal Way To Draw A Linked List Example CA EDB firstNode Link or pointer field of node Data field of node NULL 24 / 79
  • 50. Images/cinvestav- Actually, we know this as a Chain First A chain is a linked list in which each node represents one element. Second There is a link or pointer from one element to the next. Third The last node has a null pointer. 25 / 79
  • 51. Images/cinvestav- Actually, we know this as a Chain First A chain is a linked list in which each node represents one element. Second There is a link or pointer from one element to the next. Third The last node has a null pointer. 25 / 79
  • 52. Images/cinvestav- Actually, we know this as a Chain First A chain is a linked list in which each node represents one element. Second There is a link or pointer from one element to the next. Third The last node has a null pointer. 25 / 79
  • 53. Images/cinvestav- Code for ChainNode Code package L i n e a r L i s t ; // Using Generic in Java c l a s s ChainNode<Item>{ // package data members protected Item element ; protected ChainNode next ; // c o n s t r u c t o r s and methods come here } 26 / 79
  • 54. Images/cinvestav- The Constructors for ChainNode A classic one package L i n e a r L i s t ; // Using Generic in Java p u b l i c ChainNode (){ // Set the next node t h i s . element = n u l l ; t h i s . next = n u l l ; } p u b l i c ChainNode ( Item elem ){ // Set element t h i s . element = elem ; t h i s . next = n u l l ; } 27 / 79
  • 55. Images/cinvestav- What about the Class Chain? Code /∗∗ l i n k e d implementation of 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 ; import java . u t i l . ∗ ; // has I t e r a t o r p 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 members protected ChainNode<Item> f i r s t N o d e ; protected i n t s i z e ; // methods of Chain come here } 28 / 79
  • 56. Images/cinvestav- 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 of f i r s t N o d e and s i z e // are n u l l and 0 , r e s p e c t i v e l y } A simple example public Chain<Item> () { this.firstNode = new ChainNode<Item>(); this.size = 0; } 29 / 79
  • 57. Images/cinvestav- 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 of f i r s t N o d e and s i z e // are n u l l and 0 , r e s p e c t i v e l y } A simple example public Chain<Item> () { this.firstNode = new ChainNode<Item>(); this.size = 0; } 29 / 79
  • 58. Images/cinvestav- Outline 1 Iterators Interface Separate and Inner Class Iterator 2 Introduction Linked Representation Memory Layout 3 Operations IsEmpty() size() Get(Index) Remove Add 4 Can we simplify the code? 5 Other data structures based in the Linked List 30 / 79
  • 59. Images/cinvestav- IsEmpty() Really Simple Code /∗∗ @return true i f f l i s t i s empty ∗/ p u b l i c boolean isEmpty () { r e t u r n s i z e == 0;} 31 / 79
  • 60. Images/cinvestav- Outline 1 Iterators Interface Separate and Inner Class Iterator 2 Introduction Linked Representation Memory Layout 3 Operations IsEmpty() size() Get(Index) Remove Add 4 Can we simplify the code? 5 Other data structures based in the Linked List 32 / 79
  • 61. Images/cinvestav- size() Really Simple Code /∗∗ @return c u r r e n t number of elements in 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
  • 62. Images/cinvestav- Outline 1 Iterators Interface Separate and Inner Class Iterator 2 Introduction Linked Representation Memory Layout 3 Operations IsEmpty() size() Get(Index) Remove Add 4 Can we simplify the code? 5 Other data structures based in the Linked List 34 / 79
  • 63. Images/cinvestav- Operations: Get Example CA EDB firstNode Link or pointer field of node Data field of node NULL What to do to implement Get 1 Check Index 2 Move to the correct position For example: TempNode = firstNode.next.next.next. You actually use a loop. 3 return TempNode.element 35 / 79
  • 64. Images/cinvestav- Operations: Get Example CA EDB firstNode Link or pointer field of node Data field of node NULL What to do to implement Get 1 Check Index 2 Move to the correct position For example: TempNode = firstNode.next.next.next. You actually use a loop. 3 return TempNode.element 35 / 79
  • 65. Images/cinvestav- Process Check Index 0 ≤ index ≤ size − 1 (1) Negate the statement to use it How? 36 / 79
  • 66. Images/cinvestav- Process Check Index 0 ≤ index ≤ size − 1 (1) Negate the statement to use it How? 36 / 79
  • 67. Images/cinvestav- Move to the correct place How? CA EDB firstNode NULL TempNode=firstNode 37 / 79
  • 68. Images/cinvestav- Move to the correct place Index == 2 CA EDB firstNode NULL TempNode=firstNode index==2 38 / 79
  • 69. Images/cinvestav- Move to the correct place Index == 2 CA EDB firstNode NULL TempNode=TempNode.next index==2 39 / 79
  • 70. Images/cinvestav- Move to the correct place Index == 2 CA EDB firstNode NULL TempNode=TempNode.next index==2 40 / 79
  • 71. Images/cinvestav- Move to the correct place Index == 2 CA EDB firstNode NULL return TempNode.element index==2 41 / 79
  • 72. Images/cinvestav- Code Here is the method p u b l i c <Item> get ( i n t index ){ ChainNode<Item> TempNode ; //Check always i 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 ( " Index ␣ out ␣ of ␣bound " ) ; System . e x i t ( 0 ) ; } //Move to the c o r r e c t p o s i t i o n TempNode = t h i s . f i r s t N o d e ; f o r ( i n t i =0 ; i <index ; i ++){ TempNode = TempNode . next ; } r e t u r n TempNode . element ; } 42 / 79
  • 73. Images/cinvestav- Outline 1 Iterators Interface Separate and Inner Class Iterator 2 Introduction Linked Representation Memory Layout 3 Operations IsEmpty() size() Get(Index) Remove Add 4 Can we simplify the code? 5 Other data structures based in the Linked List 43 / 79
  • 74. Images/cinvestav- Now, Remove We have two cases Any ideas? Case I Removing from the beginning. Case II Remove from the middle. 44 / 79
  • 75. Images/cinvestav- Now, Remove We have two cases Any ideas? Case I Removing from the beginning. Case II Remove from the middle. 44 / 79
  • 76. Images/cinvestav- Now, Remove We have two cases Any ideas? Case I Removing from the beginning. Case II Remove from the middle. 44 / 79
  • 77. Images/cinvestav- Case I: Remove(0) Process 1 if index == 0 do 1 TempNode = firstNode 2 firstNode=firstNode.next 3 TempNode.next=NULL 4 return TempNode.element 45 / 79
  • 78. Images/cinvestav- Case I: Remove(0) Process 1 if index == 0 do 1 TempNode = firstNode 2 firstNode=firstNode.next 3 TempNode.next=NULL 4 return TempNode.element 45 / 79
  • 79. Images/cinvestav- Case I: Remove(0) Process 1 if index == 0 do 1 TempNode = firstNode 2 firstNode=firstNode.next 3 TempNode.next=NULL 4 return TempNode.element 45 / 79
  • 80. Images/cinvestav- Case I: Remove(0) Process 1 if index == 0 do 1 TempNode = firstNode 2 firstNode=firstNode.next 3 TempNode.next=NULL 4 return TempNode.element 45 / 79
  • 81. Images/cinvestav- Case I: Remove(0) Process 1 if index == 0 do 1 TempNode = firstNode 2 firstNode=firstNode.next 3 TempNode.next=NULL 4 return TempNode.element 45 / 79
  • 85. Images/cinvestav- Process return TempNode.element CA EDB firstNode NULL return TempNode.element NULL 49 / 79
  • 86. Images/cinvestav- Case II: Remove(2) Process 1 Check Index 2 Starting at the first node 3 TempNode=firstNode; 4 Loop doing 1 beforeNode=TempNode; 2 TempNode=TempNode.next; 5 before.next = TempNode.next 6 TempNode.next = NULL 7 return TempNode.element 50 / 79
  • 87. Images/cinvestav- Case II: Remove(2) Process 1 Check Index 2 Starting at the first node 3 TempNode=firstNode; 4 Loop doing 1 beforeNode=TempNode; 2 TempNode=TempNode.next; 5 before.next = TempNode.next 6 TempNode.next = NULL 7 return TempNode.element 50 / 79
  • 88. Images/cinvestav- Case II: Remove(2) Process 1 Check Index 2 Starting at the first node 3 TempNode=firstNode; 4 Loop doing 1 beforeNode=TempNode; 2 TempNode=TempNode.next; 5 before.next = TempNode.next 6 TempNode.next = NULL 7 return TempNode.element 50 / 79
  • 89. Images/cinvestav- Case II: Remove(2) Process 1 Check Index 2 Starting at the first node 3 TempNode=firstNode; 4 Loop doing 1 beforeNode=TempNode; 2 TempNode=TempNode.next; 5 before.next = TempNode.next 6 TempNode.next = NULL 7 return TempNode.element 50 / 79
  • 90. Images/cinvestav- Case II: Remove(2) Process 1 Check Index 2 Starting at the first node 3 TempNode=firstNode; 4 Loop doing 1 beforeNode=TempNode; 2 TempNode=TempNode.next; 5 before.next = TempNode.next 6 TempNode.next = NULL 7 return TempNode.element 50 / 79
  • 91. Images/cinvestav- Case II: Remove(2) Process 1 Check Index 2 Starting at the first node 3 TempNode=firstNode; 4 Loop doing 1 beforeNode=TempNode; 2 TempNode=TempNode.next; 5 before.next = TempNode.next 6 TempNode.next = NULL 7 return TempNode.element 50 / 79
  • 92. Images/cinvestav- Case II: Remove(2) Process 1 Check Index 2 Starting at the first node 3 TempNode=firstNode; 4 Loop doing 1 beforeNode=TempNode; 2 TempNode=TempNode.next; 5 before.next = TempNode.next 6 TempNode.next = NULL 7 return TempNode.element 50 / 79
  • 93. Images/cinvestav- Case II: Remove(2) Process 1 Check Index 2 Starting at the first node 3 TempNode=firstNode; 4 Loop doing 1 beforeNode=TempNode; 2 TempNode=TempNode.next; 5 before.next = TempNode.next 6 TempNode.next = NULL 7 return TempNode.element 50 / 79
  • 94. Images/cinvestav- Case II: Remove(2) Process 1 Check Index 2 Starting at the first node 3 TempNode=firstNode; 4 Loop doing 1 beforeNode=TempNode; 2 TempNode=TempNode.next; 5 before.next = TempNode.next 6 TempNode.next = NULL 7 return TempNode.element 50 / 79
  • 96. Images/cinvestav- Process: index == 2 beforeNode=TempNode; TempNode=TempNode.next; CA EDB firstNode NULL beforeNode=TempNode TempNode=TempNode.next index==2 52 / 79
  • 97. Images/cinvestav- Process: index == 2 beforeNode=TempNode; TempNode=TempNode.next; CA EDB firstNode NULL beforeNode=TempNode TempNode=TempNode.next index==2 53 / 79
  • 98. Images/cinvestav- Process: index == 2 before.next = TempNode.next CA EDB firstNode NULL beforeNode.next=TempNode.next 54 / 79
  • 99. Images/cinvestav- Process: index == 2 TempNode.next = NULL CA EDB firstNode NULL TempNode=TempNode.next NULL 55 / 79
  • 100. Images/cinvestav- Process: index == 2 TempNode.next = NULL CA EDB firstNode NULL return TempNode.element NULL 56 / 79
  • 101. Images/cinvestav- Outline 1 Iterators Interface Separate and Inner Class Iterator 2 Introduction Linked Representation Memory Layout 3 Operations IsEmpty() size() Get(Index) Remove Add 4 Can we simplify the code? 5 Other data structures based in the Linked List 57 / 79
  • 102. Images/cinvestav- Now, Add We have four cases Any ideas? Case I The Chain is Empty Case II Add at the beginning. 58 / 79
  • 103. Images/cinvestav- Now, Add We have four cases Any ideas? Case I The Chain is Empty Case II Add at the beginning. 58 / 79
  • 104. Images/cinvestav- Now, Add We have four cases Any ideas? Case I The Chain is Empty Case II Add at the beginning. 58 / 79
  • 105. Images/cinvestav- Now, Add We have four cases Any ideas? Case III Add at the middle. Case IV Add at the end. 59 / 79
  • 106. Images/cinvestav- Now, Add We have four cases Any ideas? Case III Add at the middle. Case IV Add at the end. 59 / 79
  • 107. Images/cinvestav- Now, Add We have four cases Any ideas? Case III Add at the middle. Case IV Add at the end. 59 / 79
  • 108. Images/cinvestav- Why? Think About it!!! Remember you have a sequential access. 60 / 79
  • 109. Images/cinvestav- Add at an empty list Steps 1 Create a node to store the element, NewNode 2 Then assign firstNode = NewNode 61 / 79
  • 110. Images/cinvestav- Add at an empty list Steps 1 Create a node to store the element, NewNode 2 Then assign firstNode = NewNode 61 / 79
  • 111. Images/cinvestav- Add at an empty list Steps 1 Create a node to store the element, NewNode 2 Then assign firstNode = NewNode firstNode K NULL 61 / 79
  • 112. Images/cinvestav- Add At the Beginning Steps 1 Create a node to store the element, NewNode 2 Do NewNode.next = firstNode 3 Then reassign firstNode = NewNode 4 Then, size = size +1 62 / 79
  • 113. Images/cinvestav- Add At the Beginning Steps 1 Create a node to store the element, NewNode 2 Do NewNode.next = firstNode 3 Then reassign firstNode = NewNode 4 Then, size = size +1 62 / 79
  • 114. Images/cinvestav- Add At the Beginning Steps 1 Create a node to store the element, NewNode 2 Do NewNode.next = firstNode 3 Then reassign firstNode = NewNode 4 Then, size = size +1 62 / 79
  • 115. Images/cinvestav- Add At the Beginning Steps 1 Create a node to store the element, NewNode 2 Do NewNode.next = firstNode 3 Then reassign firstNode = NewNode 4 Then, size = size +1 62 / 79
  • 116. Images/cinvestav- Add At the Beginning Steps 1 Create a node to store the element, NewNode 2 Do NewNode.next = firstNode 3 Then reassign firstNode = NewNode 4 Then, size = size +1 CA EDB firstNode NULL K 62 / 79
  • 117. Images/cinvestav- What about the other case? Do you have an idea? Add at the Middle. Add at the end. 63 / 79
  • 118. Images/cinvestav- What about the other methods? Linear List AbstractDataType LinearList { instances ordered finite collections of zero or more elements operations isEmpty(): return true iff the list is empty, false otherwise size(): return the list size (i.e., number of elements in the list) get(index): return the element with the “index” index indexOf(x): return the index of the first occurrence of x in the list, return -1 if x is not in the list remove(index): remove and return the indexth element, elements with higher index have their index reduced by 1 add(theIndex, x): insert x as the index of th element, elements with theIndex ≥ index have their index increased by 1 output(): output the list elements from left to right } 64 / 79
  • 119. Images/cinvestav- Complexity of Linked List We have Dynamic Array Linked List Amortized Analysis Indexing 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
  • 120. Images/cinvestav- Average Performance with Each Implementation on a Slow Machine!!! 40,000 Operations each type on a 350Mhz PC Operation FastArrayLinearList Chain average get 5.6 ms 157 sec average adds 5.8 sec 115 sec average removes 5.8 sec 157 sec 66 / 79
  • 121. Images/cinvestav- Can we simplify the code? How? We would like to simplify the code.... How? What about 67 / 79
  • 122. Images/cinvestav- Can we simplify the code? How? We would like to simplify the code.... How? What about CA EDB headerNode NULL 67 / 79
  • 123. Images/cinvestav- Can we simplify the code? Then, the empty list looks like headerNode Thus This simplify a lot the code because everything is a middle node 68 / 79
  • 124. Images/cinvestav- Can we simplify the code? Then, the empty list looks like headerNode Thus This simplify a lot the code because everything is a middle node 68 / 79
  • 125. Images/cinvestav- Circular List Circular List CA EDB firstNode lastNode 69 / 79
  • 126. Images/cinvestav- Here, we need to have the following changes We need to add the following to the class /∗∗ l i n k e d implementation of 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 ; import java . u t i l . ∗ ; // has I t e r a t o r p 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 members protected ChainNode<Item> f i r s t N o d e ; protected ChainNode<Item> lastNode ; protected i n t s i z e ; // methods of Chain come here } 70 / 79
  • 127. Images/cinvestav- Example of add(index) at the end Process Check if (index==size-1) Next Make the lastNode.next = TempNode Then TempNode.next = firstNode 71 / 79
  • 128. Images/cinvestav- Example of add(index) at the end Process Check if (index==size-1) Next Make the lastNode.next = TempNode Then TempNode.next = firstNode 71 / 79
  • 129. Images/cinvestav- Example of add(index) at the end Process Check if (index==size-1) Next Make the lastNode.next = TempNode Then TempNode.next = firstNode 71 / 79
  • 130. Images/cinvestav- Example of add(index) at the end Finally lastNode = TempNode 72 / 79
  • 131. Images/cinvestav- Circular List Add at the end CA EDB firstNode lastNode F lastNode.next = TempNode TempNode 73 / 79
  • 132. Images/cinvestav- Circular List Add at the end CA EDB firstNode lastNode F TempNode.next = firstNode TempNode 74 / 79
  • 133. Images/cinvestav- Circular List Add at the end CA EDB firstNode F lastNode=TempNode 75 / 79
  • 134. Images/cinvestav- We have other representations for the lists Doubly Linked List You have two chain list going through the nodes. It has a firstNode It has a lastNode Doubly Linked Circular List You have two chain list going through the nodes. It has a firstNode 76 / 79
  • 135. Images/cinvestav- We have other representations for the lists Doubly Linked List You have two chain list going through the nodes. It has a firstNode It has a lastNode Doubly Linked Circular List You have two chain list going through the nodes. It has a firstNode 76 / 79
  • 136. Images/cinvestav- Doubly Linked List Doubly Linked List CA EDB firstNode lastNode NULL NULL What about the changes here 77 / 79
  • 137. Images/cinvestav- Doubly Linked Circular List Doubly Linked Circular List CA EDB firstNode 78 / 79
  • 138. Images/cinvestav- Where does Java has all these things? Package java.util.LinkedList There you have It 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
  • 139. Images/cinvestav- Where does Java has all these things? Package java.util.LinkedList There you have It 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
  • 140. Images/cinvestav- Where does Java has all these things? Package java.util.LinkedList There you have It 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