Professional Documents
Culture Documents
Linked List
• In the Procedural Paradigm a linked list consisted of:
– A pointer to the head of the list
– Nodes (in dynamic memory i.e. the heap) containing data and
additional next pointers
– Modules that would perform a variety of functions as needed:
add (in order), traverse, find, delete, etc.
name = "Bob"
sr gpa = 3.5
ssn = 123456789
Tracing
Node n1 = new Node(null);
name = "Bob"
sr gpa = 3.5
ssn = 123456789
data
n1
next
Tracing
n1.setData(sr);
name = "Bob"
sr gpa = 3.5
ssn = 123456789
data
n1
next
Tracing
sr = new StudentRecord("Mary", 3.7, 987654321);
data
n1
next
Tracing
Node n2 = new Node(sr);
data
n1
next
data
n2
next
Tracing
n1.setNext(n2);
data
n1
next
data
n2
next
Key to Understanding Java
• Understand that the "variables" that you may think of
as objects (not primitives) are ALWAYS references
(like pointers) to objects which live in the heap.
public LinkedList() {
setHead(null);
} // constructor
private void setHead(Node head) {
this.head = head;
} // setHead
private Node getHead() {
return head;
} // getHead
LinkedList (add method)
// Purpose: add in order by SSN
// Postcon: list will contain one additional item
public void add(StudentRecord sr) {
if(getHead() == null ||
getHead().getData().getSsn() > sr.getSsn() )
{
Node temp = new Node(sr);
temp.setNext(getHead());
setHead(temp);
}
else
{
add(getHead(), sr);
}
} // add
LinkedList (add helper method)
// Purpose: add helper
private void add(Node cur, StudentRecord sr) {
if( cur.getNext() == null ||
cur.getNext().getData().getSsn() > sr.getSsn() )
{
Node temp = new Node(sr);
temp.setNext(cur.getNext());
cur.setNext(temp);
}
else
{
add(cur.getNext(), sr);
}
} // add
LinkedList (traverse )
// Purpose: traverse list
// Postcon: no change to list
public void traverse() {
traverse(getHead());
} // traverse
} // menuloop
Application
public static void main(String args[]) {
menuloop();
}
} // class Application
Diagram
class Application class LinkedList class LLNode
menuloop { LLNode head StuRec data
LinkedList list LLNode next
} methods…
main { methods…
menuloop()
}
I
In
Ins
nsta
s t
t
anc
anc
nc
e
e
e
of
of
of
LinkedList object LLNode object LLNode object
StuRec data StuRec data
head LLNode next LLNode next