ADT List
ADT List
• Specifications for the ADT List
A li t id t i d t • A list provides a way to organize data
– List of students – List of sales – List of lists
A li t h fi t l t d i b t it (th it h iti ) • A list has first , last , and in between items (the items has positions) • Operations on lists
– Add new entry – at end, or anywhere – Remove an item
– Remove all items – Replace an entry – Look at any entry
– Look for an entry of a specific value – Count how many entries
ADT List
ADT List
• To specify an ADT list
To specify an ADT list
– Describe its data
Specify the operations – Specify the operations
• ADT list must be considered in general
f
an interface for the ADT list.
• After redefine the draft specifications and it is become complete we can starting to build the Java interface for the list ADT as follows:
/** an interface for the ADT list
/ an interface for the ADT list.
* entries in the list have positions that begin with 0. * /
public interface ListInterface{
/** T k dd t t th d f th li t i th l th b 1
/** Task: adds a new entry to the end of the list .increase the length by 1
*@ param newEntry the object to be added as a new entry
*@return true if the addition is successful ( list not full), false otherwise
*/
public boolean add (Object newEntry); public boolean add (Object newEntry);
/** Task: adds a new entry at a specified position within the list. * The list size increased by 1.
*@param newPosition an integer that specifies the desired position of the new entry ; *@param newEntry the object to be added as a new entry
*@return true if the addition is successful (newPosition >= 0 and newPosition <= * getLength (), and the list not full), or false if not
an interface for the ADT list.
/** Task: removes the entry at a given position from the list. decrease the length by 1
*@param givenPosition an integer that indicates the position of the entry to be * removed;removed;
*@return either the entry at position givenPosition (if the list not empty && the
* givenPosition >=0 && the givenPosition< getLength()), otherwise return null
*/
public Object remove (int givenPosition); public Object remove (int givenPosition);
/** Task: Removes all entries from the list. */
public void clear();
/** Task: replaces the entry at a given position in the list.
*@param givenPosition an integer that indicates the position of the entry to be * replaced;
*@ E t th bj t th t ill l th t t th iti i P iti *@param newEntry the object that will replace the entry at the position givenPosition *@return true if the replacement occurs (givenPosition >= 0 and givenPosition <
* getLength() and the list not empty), or false if either the list was empty
* or givenPosition is invalid
an interface for the ADT list.
an interface for the ADT list.
/** Task: retrieves the entry at a given position in the list.
*@param givenPosition an integer that indicates the position of the desired entry;@param givenPosition an integer that indicates the position of the desired entry; *@return a reference to the indicated list entry, if (the list not empty and
* givenPosition >= 0 and givenPosition < getLength() and the entry found ,
* otherwise returns null
*//
public Object getEntry (int givenPosition);
/** Task: determines whether the list contains a given entry. *@ E t th bj t th t i th d i d t
*@param anEntry the object that is the desired entry
*@return true if (the list not empty and the list contains anEntry), or false if not */
public boolean contains (Object anEntry);
/** Task: gets the length of the list.
an interface for the ADT list.
an interface for the ADT list.
/** Task: determines whether the list is empty.p y *@return true if the list is empty, or false if not */
public boolean isEmpty();
/** Task: determines whether the list is full. *@return true if the list is full, or false if not *//
public boolean isFull();
/** Task: displays all entries that are in the list, one per line, in the order in which p y p * they occur in the list.
*/
LIST Implementations
• List ADT can be implemented using:
Fi d Si A i l t ti
– a Fixed-Size Array implementation
– Dynamic Array Expansion implementation – a Vector implementation
Using Linked – based List ADT Implementation
• Linked list is a linear data structure of
objects (items), each item is called a node.
j
(
),
• Each node contains two fields:
– a reference to an entry in the list (information – a reference to an entry in the list (information
field, data portion )
logical view of linked listog ca e o ed st
NODE
Data Link portion Null pointer Data
portion
Link portion /next (internal
pointer) External
pointer
logical view of linked listog ca e o ed st
• firstNode
(head reference ): is an external
• firstNode
(head reference ): is an external
reference that points to the first node of
the list
the list.
• Next
: is an internal reference that points to
the next node
the next node
• The next portion of the last node of the list
h
l
f
ll (d
’t
i t t
Example
Example
A Linked Implementation of the ADT List
A Linked Implementation of the ADT List
• Use a chain of nodes
Use a chain of nodes
– Remember the address of the first node in the chain
chain
• Record a reference to the first node
The “head reference” – The head reference
• The implementation contains the class
N d
i
l
A Linked Implementation of the ADT List
A Linked Implementation of the ADT List
• We can use the concept of performing
We can use the concept of performing
chains, in order to implement our
ListInterfase with its all methods
ListInterfase with its all methods.
• add new entry (new node ) in the list
1
t th b
i
i
- case 1: at the beginning
- case 2 : at the middle
A Linked Implementation of the ADT List
A Linked Implementation of the ADT List
• Remove an entry (node) from the List
Remove an entry (node) from the List
– Case 1: at the beginning Case 2: at the middle
– Case 2: at the middle – Case 3: at the end
M th d
l
• Method
replace
• Method
getEntry
• Method
contains
……
.and
Remaining
add new entry (new node ) in the list
at the beginning 1
Case
• need: null
1
- new node
- first node reference
2
1
• Process:
- get new node - store data
- connect:
add new entry (new node ) in the list
t th iddl
2
C 2 at the middle
Case
• need:
d - new node
- previous node reference - after node
• Process: • Process:
- get new node - store data
- get previous nodeget previous node
- previousNode= getNodeAt(pos -1) - get after node
- afterNode= previousNode.nextp - connect
add new entry (new node ) in the list
: at the end 3
Case
• In this case we can use two approaches:
In this case we can use two approaches:
1.
the same process As case 2.2
Get a reference to the last node as part of the2.
Get a reference to the last node as part of the implementation class ( will be explained later on).Remove an entry (node) from the List
C 1 h b i i
Case 1: at the beginning
• Process:Process:
• get data stored in the firstNode – Result = firstNode.dataResult firstNode.data
• reconnect
Remove an entry (node) from the List : at the middle
2 Case
• Process:Process:
• get node before the deleted node – beforeNode=getNodeAt(pos-1)beforeNode getNodeAt(pos 1)
• get node to be removed
– nodeToremove=beforeNode.next
• get node after deleted node – afterNode=nodeToremove.next
• reconnect
Remove an entry (node) from the List
t th
iddl
2
C
2
: at the middle
Remove an entry (node) from the List : at the end
3 Case
– In this case , what we need is to get theIn this case , what we need is to get the
reference to the node which is before the last node, so we can use the same process as
Replace operation
Replace operation
• Process:
Process:
• Get a reference to the desired node,
where the old data of this node will be
where the old data of this node will be
replaced by new data.
d i dN d tN d At(P iti )
– desiredNode = getNodeAt(Position);
• Store the new data in the data portion of
the desired node.
Get an entry from the list
Get an entry from the list
• Process
Process
• Get a reference to the desired node,
where the data of this node will be
where the data of this node will be
returned to the user.
– desiredNode = getNodeAt(Position);g ( );
• Get the data portion of this node
– result = desiredNode.data;esu t des ed ode data;
• Return the result
Contains operation
Contains operation
• Process:
Process:
• Get a referance to the firstNode
tN d fi tN d
– currentNode= firstNode;
– Using this reference (currentNode) to traverse all nodes of the list with equality comparison all nodes of the list with equality comparison
– While (not found && not reach the end of the list(currentNode != null )) { compare and If found return true else proceeds to the next node (currentNode = currentNode.next)
Is full, is empty and get length operations
Is full, is empty and get length operations
• isFull():isFull(): always return fall as no limitations on the listalways return fall as no limitations on the list size
– {return false;}
• isEmpty(): if the first node has a null value means that
the list hasn’t any node (the list empty – { return firstNode == null;}
• getLength(): returns the value of the counter that holds the number of nodes in the list
Node Class
• It is implementation detail of the ADT list
It is implementation detail of the ADT list
that should be hidden from the client:
in a package with the implementation class – in a package with the implementation class
– inner private class (the data fields of inner class are accessible directly by the outer class)
The class Node as an inner class (private Class)
private class Node{
private Object data; // data portion
private Node next; // link to next node
private Node(Object dataPortion){ private Node(Object dataPortion){ data = dataPortion;
next = null;
} // d t t
} // end constructor
private Node(Object dataPortion, node nextNode){ data = dataPortion;
next = nextNode; } // end constructor
the implementation class
public class LList implements ListInterface{
public class LList implements ListInterface{ private Node firstNode; // reference to first node
private int length; // number of entries in list
private int length; // number of entries in list
public Llist(){ clear();
clear();
} // end default constructor
<<private class Node>> // I l h
//---private!---implementation continue
/** Task: returns a reference to the node at a given position.
• precondition: list is not empty; 0 <= givenPosition < length.
• *//
private Node getNodeAt(int givenPosition){ node currntNode=firstNode;
// traverse the list to locate the desired node
for (int i =0 ; i< givenposition ; i++)
tN d t d t
implementation continue
public boolean isFull() /*always false. no limit. The system can only produce an error*/
p () y y y p
{ return false; }
public int getLength() public int getLength()
{ return length; }
public boolean isEmpty() //like ArList
public boolean isEmpty() //like ArList
{ return length == 0; }
public final void clear() public final void clear() { firstNode = null;
implementation continue
public boolean add (Object newEntry){
p ( j y){
Node newNode = new Node(newEntry); if (isEmpty())
fi tN d N d
firstNode = newNode;
else { // add to end of nonempty list
Node lastNode = getNodeAt (length - 1); Node lastNode getNodeAt (length 1);
lastNode.next = newNode; // make last node reference new node
} // end if
public boolean add (int newPosition, Object newEntry){
b l i S f l t
implementation continue
boolean isSuccessful = true;
if ((newPosition >= 0) && (newPosition <= length)){ Node newNode = new Node(newEntry);
if (isEmpty() || (newPosition= = 0)) { // case 1
if (isEmpty() || (newPosition= = 0)) { // case 1
newNode.next = firstNode; firstNode = newNode; }
else { // case 2 and 3: newPosition >= 1 list is not empty
else { // case 2 and 3: newPosition > 1, list is not empty
Node prevNode = getNodeAt (newPosition -1); Node nodeAfter = prevNode.next;
newNode.next = afterNode;; prevNode.next= newNode; } // end second if
length ++; } // end first if
else
public Object remove (int givenPosition){
implementation continue
object result = null; // returned value
if (!isEmpty() && (givenPosition >= 0) && (givenPosition <length)){ if (givenPosition = = 0) { // case 1: remove first entry
l fi N d d
result = firstNode.data; // save data of entry before removing
firstNode = firstNode.next; }
else { // case 2 and 3: givenPosition >= 1
Node prevNode = getNodeAt (givenPosition 1); Node prevNode = getNodeAt (givenPosition -1); Node nodeToRemove = prevNode.next;
Node afterNode = nodeToRemove.next;
prevNode next = afterNode; // disconnect the node to be removed
prevNode.next afterNode; // disconnect the node to be removed
result = nodeToRemove.data; // save data of entry before removing
} // end second if
length --;g ; } // end first if
return result; // return data of removed entry, or null if operation fails
implementation continue
public boolean replace (int givenPosition, Object newEntry){
boolean isSuccessful = true;
if(!isEmpt () && (gi enPosition > 0) && (gi enPosition <length)) if(!isEmpty() && (givenPosition >= 0) && (givenPosition <length)) {
Node desiredNode = getNodeAt (givenPosition); desiredNode.data = newEntry;
} else else
isSuccessful = false;
implementation continue
public Object getEntry (int givenPosition) { Object result = null; // result to return
if (!i E t () && ( i P iti 0) && ( i P iti l th)) if (!isEmpty() && (givenPosition>= 0) && (givenPosition < length)) result = getNodeAt(givenPosition).data;
return result;
} // end getEntry
public void display() p p y()
{ Node currentNode = firstNode; for( int i = 0; i <length; i++)
{ System.out.println(currentNode.data); { Syste out p t (cu e t ode data);
implementation continue
public boolean contains(Object anEntry){
boolean found = false;
Node currentNode= firstNode;
while (!found && (currentNode != null)){ if (anEntry. equals(currentNode.data)) found = true;
else
currentNode = currentNode.next; } // end while
return found;; } // end contains
Linked-based implementation of ADT List
ith T il R f
with Tail References
• Consider a set of data where we repeatedly add data to the end of the list
E h ti th tN d At th d t t th h l li t
• Each time the getNodeAt method must traverse the whole list
– This is inefficient
• Solution: maintain a pointer that always keeps track of the end of the chain
– The tail reference
A linked chain with a head and tail reference
• When adding to an empty list
– Both head and tail references must point to the new solitary node
• When adding to a non empty list
Adding a node to the end of a nonempty chain that has a tail reference
Removing a node from a chain that has both head
d t il f
and tail references
when the chain contains (a) one node; (b) more
the implementation class with tail reference
t e p e e tat o c ass t ta e e e ce
• The code is written only for methods that have been y changed.
public class LList implements ListInterface{
public class LList implements ListInterface{
private Node firstNode; // refrence to first node
private node lastNode;
p ;
private int length; // number of entries in list
public Llist(){
Note: the underlined text shows the difference at the previous implementation
p (){ clear();
} // end default constructor
implementation continue
public Boolean add (Object newEntry){
Node newNode = new Node(newEntry); if (isEmpty()) {
firstNode = newNode;
}
else { // add to end of nonempty list
// Node lastNode = getNodeAt(length -1); omittedg ( g )
lastNode.next = newNode; // make last node reference new node
} // end if
lastNode =newNode;;
length++;
return true; Note: the underlined text
public Boolean add(int newPosition, Object newEntry){
boolean isSuccessful = true;
if ((newPosition >= 0) && (newPosition <= length)){
implementation continue
if ((newPosition 0) && (newPosition length)){ Node newNode = new Node(newEntry);
If (isEmpty){
// If (isEmpty()) || (newPosition= = 0)) { // case 1 //NewNode.next = firstNode; omitted
FirstNode = newNode;
lastNod=newNode;}
Else if(newPosition= = 0){
newNode.next=firstNode; firstNode=newNode;
}
else if (newposition==length){ lastnode.next=newNoe;
lastNode=newNode;} lastNode=newNode;}
else { // case 2: newPosition > 0 and <length, list is not empty Node prevNode = getNodeAt(newPosition-1);
Node after = prevNode.next; newNode.next = afterNode; prevNode.next= newNode; } // end if
length++;} else
public Object remove(int givenPosition){
Object result = null; // returned value
f ( () && ( 0) && ( )){
implementation continue
if (!isEmpty() && (givenPosition >= 0) && (givenPosition <length)){ if (givenPosition = = 0) { // case 1: remove first entry
result = firstNode.data; // save entry to be removed firstNode = firstNode.next;
firstNode firstNode.next;
if(legth ==1)
lastNode=null; // the list become empty
}
l { // 2 d 3 i P iti 0 else { // case 2 and 3: givenPosition > 0
Node prevNode = getNodeAt(givenPosition-1); Node nodeToRemove = prevNode.next;
Node afterNode = nodeToRemove.next;;
prevNode.next = afterNode; // disconnect the node to be removed result = nodeToRemove.data; //save entry to be removed
if(givenposition== length-1);
lastNode = prevNode; Note: the underlined text
lastNode = prevNode;
} // end if length - -; } // end if
Note: the underlined text shows the difference at the previous implementation
Pros and Cons of a Chain for an ADT List
• The chain (list) can grow as large as necessary (advantage)
C f
• Can add and remove nodes without shifting existing entries (advantage)
• But …
• Must traverse a chain to determine where to make addition/deletion (disadvantage)
• Retrieving an entry requires traversal • Retrieving an entry requires traversal
Java Class Library: The Class LinkedList
Java Class Library: The Class LinkedList
• The standard java package java.util contains the class LiknkedList
• This class implements the interface List • Contains additional methods
()
• addFirst()
• addLast()
• removeFirst()
• removeLast()
• getFirst()