Singly Linked List ( 4.4.1)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Singly Linked List (§ 4.4.

1)
A singly linked list is a
concrete data structure next
Linked Lists consisting of a sequence
of nodes
Each node stores
„ element elem node
„ link to the next node

A B C D

© 2004 Goodrich, Tamassia Linked Lists 1 © 2004 Goodrich, Tamassia Linked Lists 2

The Node Class for List Nodes Inserting at the Head


public class Node {
// Instance variables:
private Object element;
private Node next;
1. Allocate a new
/** Creates a node with null references to its element and next node. */
public Node()
this(null, null);
{ node
2. Insert new element
}
/** Creates a node with the given element and next node. */
public Node(Object e, Node n) {

3. Have new node


element = e;
next = n;
}
// Accessor methods:
public Object getElement() {
return element;
point to old head
}
public Node getNext() {

}
return next; 4. Update head to
// Modifier methods:
public void setElement(Object newElem) { point to new node
element = newElem;
}
public void setNext(Node newNext) {
next = newNext;
}
}

© 2004 Goodrich, Tamassia Linked Lists 3 © 2004 Goodrich, Tamassia Linked Lists 4
Removing at the Head Inserting at the Tail
1. Allocate a new
1. Update head to
node
point to next node
in the list 2. Insert new element
2. Allow garbage 3. Have new node
collector to reclaim point to null
the former first 4. Have old last node
node point to new node
5. Update tail to point
to new node

© 2004 Goodrich, Tamassia Linked Lists 5 © 2004 Goodrich, Tamassia Linked Lists 6

Removing at the Tail Stack with a Singly Linked List


We can implement a stack with a singly linked list
Removing at the tail The top element is stored at the first node of the list
of a singly linked list The space used is O(n) and each operation of the
is not efficient! Stack ADT takes O(1) time
There is no
nodes
constant-time way
to update the tail to t ∅
point to the previous
node

elements

© 2004 Goodrich, Tamassia Linked Lists 7 © 2004 Goodrich, Tamassia Linked Lists 8
Queue with a Singly Linked List
We can implement a queue with a singly linked list
„ The front element is stored at the first node
„ The rear element is stored at the last node
The space used is O(n) and each operation of the
Queue ADT takes O(1) time r
nodes

f ∅

elements
© 2004 Goodrich, Tamassia Linked Lists 9

You might also like