Documente Academic
Documente Profesional
Documente Cultură
FUNDAMENTALS OF
DATA STRUCTURES
Topic 3:
Linked List (Part 2)
LINKED LIST OPERATIONS
(COUNTING - SIZE)
Counting all data
Traversing a linked list
// traverse the whole list and count all data
public int size()
{
int size = 0;
Node ptr ; // the external pointer
return size;
}
Test Yourself
while (ptr!=null)
{ System.out.println(ptr.data.toString());
ptr = ptr.next;
}
}
LINKED LIST OPERATIONS
(ACCESS & RETRIEVE)
Methods for retrieval
• These methods will use the current data field
public class LinkList
{ private class Node
{ ….
}
Node head;
Node current; // this field will be used
…
}
• Node current is used to point to the current node
being processed
Retrieve the front
Retrieve data at the front of the list
if (current != null)
{ info = current.data;
current = current.next;
}
return info;
}
Retrieve after a specific node
Retrieve data after a node
// gets the data in the node pointed by specified node
// and points current to the next node
if (p != null)
{
x = p.next;
info = x.data;
}
return info;
}
Retrieve the last
Test Yourself - Retrieve
if (isEmpty())
{
System.err.println(“The list is empty");
return info;
}
else
{
Node ptr = head; //last node
info = ptr.data;
return info;
}
}
GENERIC CLASS
VS
SPECIFIC CLASS
• if the LinkList class has been designed to
be generic (ie. the data type is Object),
only generic methods could be written
• if the LinkedList class has been declared
specifically for one type of data eg. Student
data, specific methods to process Student
data in class LinkList can be written