SlideShare a Scribd company logo
1 of 140
Download to read offline
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-
Eļ¬€ect in a list
Before next()
Joes Piotor Iterator cursor Jen Jess Marius
After next()
Joes Piotor Jen Iterator cursor Jess Marius
Eļ¬€ect of remove()
Joes Piotor Iterator cursor Jess Marius
10 / 79
Images/cinvestav-
Eļ¬€ect in a list
Before next()
Joes Piotor Iterator cursor Jen Jess Marius
After next()
Joes Piotor Jen Iterator cursor Jess Marius
Eļ¬€ect of remove()
Joes Piotor Iterator cursor Jess Marius
10 / 79
Images/cinvestav-
Eļ¬€ect in a list
Before next()
Joes Piotor Iterator cursor Jen Jess Marius
After next()
Joes Piotor Jen Iterator cursor Jess Marius
Eļ¬€ect 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 deļ¬ne 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 diļ¬€erent 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 deļ¬ne 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 diļ¬€erent 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 deļ¬ne 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 diļ¬€erent 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 deļ¬ne 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 diļ¬€erent 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 stuļ¬€ 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 stuļ¬€ 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 stuļ¬€ 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 ļ¬‚ = 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 ļ¬‚ = 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 ļ¬‚ = 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 ļ¬‚ = 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
ļ¬rstNode
First
Last pointer (or link) from E is null
Thus
You can use a variable ļ¬rstNode to get to the ļ¬rst element in the Linked
List.
23 / 79
Images/cinvestav-
Memory Layout
We have the following
C A E D B
ļ¬rstNode
First
Last pointer (or link) from E is null
Thus
You can use a variable ļ¬rstNode to get to the ļ¬rst element in the Linked
List.
23 / 79
Images/cinvestav-
Memory Layout
We have the following
C A E D B
ļ¬rstNode
First
Last pointer (or link) from E is null
Thus
You can use a variable ļ¬rstNode to get to the ļ¬rst element in the Linked
List.
23 / 79
Images/cinvestav-
Normal Way To Draw A Linked List
Example
CA EDB
ļ¬rstNode
Link or pointer ļ¬eld of node
Data ļ¬eld 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.ļ¬rstNode = 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.ļ¬rstNode = 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
ļ¬rstNode
Link or pointer ļ¬eld of node
Data ļ¬eld of node
NULL
What to do to implement Get
1 Check Index
2 Move to the correct position
For example: TempNode = ļ¬rstNode.next.next.next.
You actually use a loop.
3 return TempNode.element
35 / 79
Images/cinvestav-
Operations: Get
Example
CA EDB
ļ¬rstNode
Link or pointer ļ¬eld of node
Data ļ¬eld of node
NULL
What to do to implement Get
1 Check Index
2 Move to the correct position
For example: TempNode = ļ¬rstNode.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
ļ¬rstNode NULL
TempNode=ļ¬rstNode
37 / 79
Images/cinvestav-
Move to the correct place
Index == 2
CA EDB
ļ¬rstNode NULL
TempNode=ļ¬rstNode
index==2
38 / 79
Images/cinvestav-
Move to the correct place
Index == 2
CA EDB
ļ¬rstNode NULL
TempNode=TempNode.next
index==2
39 / 79
Images/cinvestav-
Move to the correct place
Index == 2
CA EDB
ļ¬rstNode NULL
TempNode=TempNode.next
index==2
40 / 79
Images/cinvestav-
Move to the correct place
Index == 2
CA EDB
ļ¬rstNode 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 = ļ¬rstNode
2 ļ¬rstNode=ļ¬rstNode.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 = ļ¬rstNode
2 ļ¬rstNode=ļ¬rstNode.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 = ļ¬rstNode
2 ļ¬rstNode=ļ¬rstNode.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 = ļ¬rstNode
2 ļ¬rstNode=ļ¬rstNode.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 = ļ¬rstNode
2 ļ¬rstNode=ļ¬rstNode.next
3 TempNode.next=NULL
4 return TempNode.element
45 / 79
Images/cinvestav-
Process
TempNode=ļ¬rstNode
CA EDB
ļ¬rstNode NULL
TempNode=ļ¬rstNode
46 / 79
Images/cinvestav-
Process
ļ¬rstNode=ļ¬rstNode.next
CA EDB
ļ¬rstNode NULL
TempNode
47 / 79
Images/cinvestav-
Process
TempNode.next=NULL
CA EDB
ļ¬rstNode NULL
TempNode NULL
48 / 79
Images/cinvestav-
Process
return TempNode.element
CA EDB
ļ¬rstNode NULL
return TempNode.element
NULL
49 / 79
Images/cinvestav-
Case II: Remove(2)
Process
1 Check Index
2 Starting at the ļ¬rst node
3 TempNode=ļ¬rstNode;
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 ļ¬rst node
3 TempNode=ļ¬rstNode;
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 ļ¬rst node
3 TempNode=ļ¬rstNode;
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 ļ¬rst node
3 TempNode=ļ¬rstNode;
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 ļ¬rst node
3 TempNode=ļ¬rstNode;
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 ļ¬rst node
3 TempNode=ļ¬rstNode;
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 ļ¬rst node
3 TempNode=ļ¬rstNode;
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 ļ¬rst node
3 TempNode=ļ¬rstNode;
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 ļ¬rst node
3 TempNode=ļ¬rstNode;
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=ļ¬rstNode
CA EDB
ļ¬rstNode NULL
TempNode=ļ¬rstNode
51 / 79
Images/cinvestav-
Process: index == 2
beforeNode=TempNode;
TempNode=TempNode.next;
CA EDB
ļ¬rstNode NULL
beforeNode=TempNode TempNode=TempNode.next
index==2
52 / 79
Images/cinvestav-
Process: index == 2
beforeNode=TempNode;
TempNode=TempNode.next;
CA EDB
ļ¬rstNode NULL
beforeNode=TempNode TempNode=TempNode.next
index==2
53 / 79
Images/cinvestav-
Process: index == 2
before.next = TempNode.next
CA EDB
ļ¬rstNode NULL
beforeNode.next=TempNode.next
54 / 79
Images/cinvestav-
Process: index == 2
TempNode.next = NULL
CA EDB
ļ¬rstNode NULL
TempNode=TempNode.next
NULL
55 / 79
Images/cinvestav-
Process: index == 2
TempNode.next = NULL
CA EDB
ļ¬rstNode 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 ļ¬rstNode = NewNode
61 / 79
Images/cinvestav-
Add at an empty list
Steps
1 Create a node to store the element, NewNode
2 Then assign ļ¬rstNode = NewNode
61 / 79
Images/cinvestav-
Add at an empty list
Steps
1 Create a node to store the element, NewNode
2 Then assign ļ¬rstNode = NewNode
ļ¬rstNode
K
NULL
61 / 79
Images/cinvestav-
Add At the Beginning
Steps
1 Create a node to store the element, NewNode
2 Do NewNode.next = ļ¬rstNode
3 Then reassign ļ¬rstNode = 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 = ļ¬rstNode
3 Then reassign ļ¬rstNode = 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 = ļ¬rstNode
3 Then reassign ļ¬rstNode = 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 = ļ¬rstNode
3 Then reassign ļ¬rstNode = 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 = ļ¬rstNode
3 Then reassign ļ¬rstNode = NewNode
4 Then, size = size +1
CA EDB
ļ¬rstNode
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 ļ¬nite collections of zero or more elements
operations
isEmpty(): return true iļ¬€ 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 ļ¬rst 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
ļ¬rstNode 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 = ļ¬rstNode
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 = ļ¬rstNode
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 = ļ¬rstNode
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
ļ¬rstNode lastNode
F
lastNode.next = TempNode
TempNode
73 / 79
Images/cinvestav-
Circular List
Add at the end
CA EDB
ļ¬rstNode
lastNode
F
TempNode.next = ļ¬rstNode TempNode
74 / 79
Images/cinvestav-
Circular List
Add at the end
CA EDB
ļ¬rstNode
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 ļ¬rstNode
It has a lastNode
Doubly Linked Circular List
You have two chain list going through the nodes.
It has a ļ¬rstNode
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 ļ¬rstNode
It has a lastNode
Doubly Linked Circular List
You have two chain list going through the nodes.
It has a ļ¬rstNode
76 / 79
Images/cinvestav-
Doubly Linked List
Doubly Linked List
CA EDB
ļ¬rstNode lastNode
NULL
NULL
What about the changes here
77 / 79
Images/cinvestav-
Doubly Linked Circular List
Doubly Linked Circular List
CA EDB
ļ¬rstNode
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

More Related Content

What's hot

Arrays in programming
Arrays in programmingArrays in programming
Arrays in programmingTaseerRao
Ā 
Presentation on queue
Presentation on queuePresentation on queue
Presentation on queueRojan Pariyar
Ā 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks QueuesIntro C# Book
Ā 
7array in c#
7array in c#7array in c#
7array in c#Sireesh K
Ā 
Python Modules, Packages and Libraries
Python Modules, Packages and LibrariesPython Modules, Packages and Libraries
Python Modules, Packages and LibrariesVenugopalavarma Raja
Ā 
Array and Collections in c#
Array and Collections in c#Array and Collections in c#
Array and Collections in c#Umar Farooq
Ā 
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 SCIENCEVenugopalavarma Raja
Ā 
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 | EdurekaEdureka!
Ā 
2 introduction to data structure
2  introduction to data structure2  introduction to data structure
2 introduction to data structureMahmoud Alfarra
Ā 
C++ STL ꦂ觀
C++ STL ꦂ觀C++ STL ꦂ觀
C++ STL ꦂ觀PingLun Liao
Ā 
Whiteboarding Coding Challenges in Python
Whiteboarding Coding Challenges in PythonWhiteboarding Coding Challenges in Python
Whiteboarding Coding Challenges in PythonAndrew Ferlitsch
Ā 

What's hot (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++
Ā 

Viewers also liked

07 Machine Learning - Expectation Maximization
07 Machine Learning - Expectation Maximization07 Machine Learning - Expectation Maximization
07 Machine Learning - Expectation MaximizationAndres Mendez-Vazquez
Ā 
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 2sashrilisdi
Ā 
Periodic table (1)
Periodic table (1)Periodic table (1)
Periodic table (1)jghopwood
Ā 
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 LearningAndres Mendez-Vazquez
Ā 
Preparation Data Structures 10 trees
Preparation Data Structures 10 treesPreparation Data Structures 10 trees
Preparation Data Structures 10 treesAndres Mendez-Vazquez
Ā 
01 Machine Learning Introduction
01 Machine Learning Introduction 01 Machine Learning Introduction
01 Machine Learning Introduction Andres Mendez-Vazquez
Ā 
What's the Matter?
What's the Matter?What's the Matter?
What's the Matter?Stephen Taylor
Ā 
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 AlgorithmsAndres Mendez-Vazquez
Ā 
13 Machine Learning Supervised Decision Trees
13 Machine Learning Supervised Decision Trees13 Machine Learning Supervised Decision Trees
13 Machine Learning Supervised Decision TreesAndres Mendez-Vazquez
Ā 
Preparation Data Structures 11 graphs
Preparation Data Structures 11 graphsPreparation Data Structures 11 graphs
Preparation Data Structures 11 graphsAndres Mendez-Vazquez
Ā 
31 Machine Learning Unsupervised Cluster Validity
31 Machine Learning Unsupervised Cluster Validity31 Machine Learning Unsupervised Cluster Validity
31 Machine Learning Unsupervised Cluster ValidityAndres Mendez-Vazquez
Ā 
23 Machine Learning Feature Generation
23 Machine Learning Feature Generation23 Machine Learning Feature Generation
23 Machine Learning Feature GenerationAndres Mendez-Vazquez
Ā 

Viewers also liked (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
Ā 

Similar to 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 - 5ecomputernotes
Ā 
Computer notes - Josephus Problem
Computer notes - Josephus ProblemComputer notes - Josephus Problem
Computer notes - Josephus Problemecomputernotes
Ā 
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 2018Codemotion
Ā 
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.pdffcaindore
Ā 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
Ā 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And AnswerJagan Mohan Bishoyi
Ā 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answerlavparmar007
Ā 
Collections
CollectionsCollections
Collectionssagsharma
Ā 
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 AndroidFernando Cejas
Ā 
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).pptxAbhishek Tirkey
Ā 
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).pptxGauravPandey43518
Ā 
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.pdfarpitaeron555
Ā 
A04
A04A04
A04lksoo
Ā 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Featuressholavanalli
Ā 
Linked list (java platform se 8 )
Linked list (java platform se 8 )Linked list (java platform se 8 )
Linked list (java platform se 8 )charan kumar
Ā 
Spl to the Rescue - Zendcon 09
Spl to the Rescue - Zendcon 09Spl to the Rescue - Zendcon 09
Spl to the Rescue - Zendcon 09Elizabeth Smith
Ā 
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.pdfkarymadelaneyrenne19
Ā 

Similar to 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
Ā 
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
Ā 
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
Ā 

More from Andres Mendez-Vazquez

01.04 orthonormal basis_eigen_vectors
01.04 orthonormal basis_eigen_vectors01.04 orthonormal basis_eigen_vectors
01.04 orthonormal basis_eigen_vectorsAndres Mendez-Vazquez
Ā 
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_issuesAndres Mendez-Vazquez
Ā 
05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiation05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiationAndres Mendez-Vazquez
Ā 
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 LearningAndres Mendez-Vazquez
Ā 
25 introduction reinforcement_learning
25 introduction reinforcement_learning25 introduction reinforcement_learning
25 introduction reinforcement_learningAndres Mendez-Vazquez
Ā 
Neural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning SyllabusNeural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning SyllabusAndres Mendez-Vazquez
Ā 
Introduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabusIntroduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabusAndres Mendez-Vazquez
Ā 
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 SciencesAndres Mendez-Vazquez
Ā 
Analysis of Algorithms Syllabus
Analysis of Algorithms  SyllabusAnalysis of Algorithms  Syllabus
Analysis of Algorithms SyllabusAndres Mendez-Vazquez
Ā 
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 variationsAndres Mendez-Vazquez
Ā 
17 vapnik chervonenkis dimension
17 vapnik chervonenkis dimension17 vapnik chervonenkis dimension
17 vapnik chervonenkis dimensionAndres Mendez-Vazquez
Ā 
A basic introduction to learning
A basic introduction to learningA basic introduction to learning
A basic introduction to learningAndres Mendez-Vazquez
Ā 

More from 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
Ā 

Recently uploaded

Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
Ā 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
Ā 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
Ā 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
Ā 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
Ā 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
Ā 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
Ā 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
Ā 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
Ā 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
Ā 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
Ā 
ā€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
ā€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...ā€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
ā€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
Ā 
ą¤­ą¤¾ą¤°ą¤¤-ą¤°ą„‹ą¤® ą¤µą„ą¤Æą¤¾ą¤Ŗą¤¾ą¤°.pptx, Indo-Roman Trade,
ą¤­ą¤¾ą¤°ą¤¤-ą¤°ą„‹ą¤® ą¤µą„ą¤Æą¤¾ą¤Ŗą¤¾ą¤°.pptx, Indo-Roman Trade,ą¤­ą¤¾ą¤°ą¤¤-ą¤°ą„‹ą¤® ą¤µą„ą¤Æą¤¾ą¤Ŗą¤¾ą¤°.pptx, Indo-Roman Trade,
ą¤­ą¤¾ą¤°ą¤¤-ą¤°ą„‹ą¤® ą¤µą„ą¤Æą¤¾ą¤Ŗą¤¾ą¤°.pptx, Indo-Roman Trade,Virag Sontakke
Ā 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
Ā 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
Ā 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
Ā 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
Ā 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
Ā 

Recently uploaded (20)

Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
Ā 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
Ā 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
Ā 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
Ā 
Model Call Girl in Bikash Puri Delhi reach out to us at šŸ”9953056974šŸ”
Model Call Girl in Bikash Puri  Delhi reach out to us at šŸ”9953056974šŸ”Model Call Girl in Bikash Puri  Delhi reach out to us at šŸ”9953056974šŸ”
Model Call Girl in Bikash Puri Delhi reach out to us at šŸ”9953056974šŸ”
Ā 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
Ā 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Ā 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
Ā 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
Ā 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
Ā 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
Ā 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
Ā 
ā€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
ā€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...ā€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
ā€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
Ā 
ą¤­ą¤¾ą¤°ą¤¤-ą¤°ą„‹ą¤® ą¤µą„ą¤Æą¤¾ą¤Ŗą¤¾ą¤°.pptx, Indo-Roman Trade,
ą¤­ą¤¾ą¤°ą¤¤-ą¤°ą„‹ą¤® ą¤µą„ą¤Æą¤¾ą¤Ŗą¤¾ą¤°.pptx, Indo-Roman Trade,ą¤­ą¤¾ą¤°ą¤¤-ą¤°ą„‹ą¤® ą¤µą„ą¤Æą¤¾ą¤Ŗą¤¾ą¤°.pptx, Indo-Roman Trade,
ą¤­ą¤¾ą¤°ą¤¤-ą¤°ą„‹ą¤® ą¤µą„ą¤Æą¤¾ą¤Ŗą¤¾ą¤°.pptx, Indo-Roman Trade,
Ā 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
Ā 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
Ā 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
Ā 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
Ā 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
Ā 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
Ā 

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- Eļ¬€ect in a list Before next() Joes Piotor Iterator cursor Jen Jess Marius After next() Joes Piotor Jen Iterator cursor Jess Marius Eļ¬€ect of remove() Joes Piotor Iterator cursor Jess Marius 10 / 79
  • 21. Images/cinvestav- Eļ¬€ect in a list Before next() Joes Piotor Iterator cursor Jen Jess Marius After next() Joes Piotor Jen Iterator cursor Jess Marius Eļ¬€ect of remove() Joes Piotor Iterator cursor Jess Marius 10 / 79
  • 22. Images/cinvestav- Eļ¬€ect in a list Before next() Joes Piotor Iterator cursor Jen Jess Marius After next() Joes Piotor Jen Iterator cursor Jess Marius Eļ¬€ect 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 deļ¬ne 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 diļ¬€erent 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 deļ¬ne 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 diļ¬€erent 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 deļ¬ne 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 diļ¬€erent 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 deļ¬ne 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 diļ¬€erent 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 stuļ¬€ 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 stuļ¬€ 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 stuļ¬€ 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 ļ¬‚ = 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 ļ¬‚ = 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 ļ¬‚ = 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 ļ¬‚ = 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 ļ¬rstNode First Last pointer (or link) from E is null Thus You can use a variable ļ¬rstNode to get to the ļ¬rst element in the Linked List. 23 / 79
  • 47. Images/cinvestav- Memory Layout We have the following C A E D B ļ¬rstNode First Last pointer (or link) from E is null Thus You can use a variable ļ¬rstNode to get to the ļ¬rst element in the Linked List. 23 / 79
  • 48. Images/cinvestav- Memory Layout We have the following C A E D B ļ¬rstNode First Last pointer (or link) from E is null Thus You can use a variable ļ¬rstNode to get to the ļ¬rst element in the Linked List. 23 / 79
  • 49. Images/cinvestav- Normal Way To Draw A Linked List Example CA EDB ļ¬rstNode Link or pointer ļ¬eld of node Data ļ¬eld 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.ļ¬rstNode = 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.ļ¬rstNode = 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 ļ¬rstNode Link or pointer ļ¬eld of node Data ļ¬eld of node NULL What to do to implement Get 1 Check Index 2 Move to the correct position For example: TempNode = ļ¬rstNode.next.next.next. You actually use a loop. 3 return TempNode.element 35 / 79
  • 64. Images/cinvestav- Operations: Get Example CA EDB ļ¬rstNode Link or pointer ļ¬eld of node Data ļ¬eld of node NULL What to do to implement Get 1 Check Index 2 Move to the correct position For example: TempNode = ļ¬rstNode.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 ļ¬rstNode NULL TempNode=ļ¬rstNode 37 / 79
  • 68. Images/cinvestav- Move to the correct place Index == 2 CA EDB ļ¬rstNode NULL TempNode=ļ¬rstNode index==2 38 / 79
  • 69. Images/cinvestav- Move to the correct place Index == 2 CA EDB ļ¬rstNode NULL TempNode=TempNode.next index==2 39 / 79
  • 70. Images/cinvestav- Move to the correct place Index == 2 CA EDB ļ¬rstNode NULL TempNode=TempNode.next index==2 40 / 79
  • 71. Images/cinvestav- Move to the correct place Index == 2 CA EDB ļ¬rstNode 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 = ļ¬rstNode 2 ļ¬rstNode=ļ¬rstNode.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 = ļ¬rstNode 2 ļ¬rstNode=ļ¬rstNode.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 = ļ¬rstNode 2 ļ¬rstNode=ļ¬rstNode.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 = ļ¬rstNode 2 ļ¬rstNode=ļ¬rstNode.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 = ļ¬rstNode 2 ļ¬rstNode=ļ¬rstNode.next 3 TempNode.next=NULL 4 return TempNode.element 45 / 79
  • 86. Images/cinvestav- Case II: Remove(2) Process 1 Check Index 2 Starting at the ļ¬rst node 3 TempNode=ļ¬rstNode; 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 ļ¬rst node 3 TempNode=ļ¬rstNode; 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 ļ¬rst node 3 TempNode=ļ¬rstNode; 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 ļ¬rst node 3 TempNode=ļ¬rstNode; 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 ļ¬rst node 3 TempNode=ļ¬rstNode; 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 ļ¬rst node 3 TempNode=ļ¬rstNode; 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 ļ¬rst node 3 TempNode=ļ¬rstNode; 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 ļ¬rst node 3 TempNode=ļ¬rstNode; 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 ļ¬rst node 3 TempNode=ļ¬rstNode; 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 ļ¬rstNode NULL beforeNode=TempNode TempNode=TempNode.next index==2 52 / 79
  • 97. Images/cinvestav- Process: index == 2 beforeNode=TempNode; TempNode=TempNode.next; CA EDB ļ¬rstNode NULL beforeNode=TempNode TempNode=TempNode.next index==2 53 / 79
  • 98. Images/cinvestav- Process: index == 2 before.next = TempNode.next CA EDB ļ¬rstNode NULL beforeNode.next=TempNode.next 54 / 79
  • 99. Images/cinvestav- Process: index == 2 TempNode.next = NULL CA EDB ļ¬rstNode NULL TempNode=TempNode.next NULL 55 / 79
  • 100. Images/cinvestav- Process: index == 2 TempNode.next = NULL CA EDB ļ¬rstNode 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 ļ¬rstNode = NewNode 61 / 79
  • 110. Images/cinvestav- Add at an empty list Steps 1 Create a node to store the element, NewNode 2 Then assign ļ¬rstNode = NewNode 61 / 79
  • 111. Images/cinvestav- Add at an empty list Steps 1 Create a node to store the element, NewNode 2 Then assign ļ¬rstNode = NewNode ļ¬rstNode 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 = ļ¬rstNode 3 Then reassign ļ¬rstNode = 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 = ļ¬rstNode 3 Then reassign ļ¬rstNode = 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 = ļ¬rstNode 3 Then reassign ļ¬rstNode = 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 = ļ¬rstNode 3 Then reassign ļ¬rstNode = 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 = ļ¬rstNode 3 Then reassign ļ¬rstNode = NewNode 4 Then, size = size +1 CA EDB ļ¬rstNode 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 ļ¬nite collections of zero or more elements operations isEmpty(): return true iļ¬€ 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 ļ¬rst 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 ļ¬rstNode 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 = ļ¬rstNode 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 = ļ¬rstNode 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 = ļ¬rstNode 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 ļ¬rstNode lastNode F lastNode.next = TempNode TempNode 73 / 79
  • 132. Images/cinvestav- Circular List Add at the end CA EDB ļ¬rstNode lastNode F TempNode.next = ļ¬rstNode TempNode 74 / 79
  • 133. Images/cinvestav- Circular List Add at the end CA EDB ļ¬rstNode 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 ļ¬rstNode It has a lastNode Doubly Linked Circular List You have two chain list going through the nodes. It has a ļ¬rstNode 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 ļ¬rstNode It has a lastNode Doubly Linked Circular List You have two chain list going through the nodes. It has a ļ¬rstNode 76 / 79
  • 136. Images/cinvestav- Doubly Linked List Doubly Linked List CA EDB ļ¬rstNode lastNode NULL NULL What about the changes here 77 / 79
  • 137. Images/cinvestav- Doubly Linked Circular List Doubly Linked Circular List CA EDB ļ¬rstNode 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