• No results found

lecture-4-ADTList-linked-implementation-2011-1.pdf

N/A
N/A
Protected

Academic year: 2020

Share "lecture-4-ADTList-linked-implementation-2011-1.pdf"

Copied!
46
0
0

Loading.... (view fulltext now)

Full text

(1)
(2)

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

(3)

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

(4)

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

(5)

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

(6)

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.

(7)

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.

*/

(8)

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

(9)

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 )

(10)

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

(11)

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

(12)

Example

Example

(13)

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

(14)

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

(15)

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

(16)

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:

(17)

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

(18)

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 the

2.

Get a reference to the last node as part of the implementation class ( will be explained later on).
(19)

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

(20)

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

(21)

Remove an entry (node) from the List

t th

iddl

2

C

2

: at the middle

(22)

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

(23)

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.

(24)

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

(25)

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)

(26)

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

(27)

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)

(28)

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

(29)

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

(30)

//---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

(31)

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;

(32)

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

(33)

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

(34)

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

(35)

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;

(36)

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);

(37)

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

(38)

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

(39)

Adding a node to the end of a nonempty chain that has a tail reference

(40)

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

(41)

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

(42)

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

(43)

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

(44)

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

(45)

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

(46)

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()

References

Related documents

Voter Judge &lt;&lt;extends&gt;&gt; Electoral Registrar &lt;&lt;uses&gt;&gt; See complete Vote record See list of candidates Vote Check eligibility Print vote summary List who..

The primary objectives of this project is to transform the huge amount of wireless and unstructured data collected from different telematics providers, Hadoop tools and data

Hence, the FCM that resulted from this study allowed the participants to: (1) identify key factors/variables of neighbor- hood satisfaction; (2) boost discussion and negotia-

the dissemination of private wells results in double tragedies in that the non-well users suffer increased poverty due to the decline in collective management of tank irrigation

Five sites were located in Terra Nova National Park (TNNP), three were near Clarenville, and two occurred on the Avalon Peninsula. Sites were found within 5 different

Only one case had absence of the stapes of superstructure and had to undergo myringoplatinopexy (type IIIc tympanoplasty) using the homologous septal cartilage

A dramatic reduction in primary energy demand compared to the International Energy Agency’s “reference scenario” (see Chapter 4) – but with the same GDP and population development

Finally, the following are the results of the Hybrid QTT, where the entity, played by both a human and a machine, has to accomplish a yes/no enquiry with as few humanlike questions