linked lists - computer science and engineeringcs2011/lect/07_linkedlists1.pdf© 2004 goodrich,...
TRANSCRIPT
Linked Lists 2© 2004 Goodrich, Tamassia
Singly Linked List (§ 4.4.1)A singly linked list is aconcrete data structureconsisting of a sequenceof nodesEach node stores element link to the next node
next
elem node
A B C D
∅
Linked Lists 3© 2004 Goodrich, Tamassia
Linked List node in Javapublic class ListNode {
Object elem;
ListNode next;
public ListNode (ListNode next, Object elem)
{this.next = next; this.elem = elem; }public Object getElem() {return elem; }
public void setElem(Object elem) {this.elem = elem; }
public ListNode getNext() {return next; }
public void setNext(ListNode next) {this.next = next; }
}
Linked Lists 4© 2004 Goodrich, Tamassia
Inserting at the Head1. Allocate a new
node2. Insert new element3. Have new node
point to old head4. Update head to
point to new node
Linked Lists 5© 2004 Goodrich, Tamassia
Removing at the Head
1. Update head topoint to next nodein the list
2. Allow garbagecollector to reclaimthe former firstnode
Linked Lists 6© 2004 Goodrich, Tamassia
Stack with a Singly Linked ListWe can implement a stack with a singly linked listThe top element is stored at the first node of the listThe space used is O(n) and each operation of the Stack ADTtakes O(1) time
∅t
nodes
elements
Linked Lists 7© 2004 Goodrich, Tamassia
Inserting at the Tail1. Allocate a new
node2. Insert new element3. Have new node
point to null4. Have old last node
point to new node5. Update tail to point
to new node
Linked Lists 8© 2004 Goodrich, Tamassia
Queue with a Singly Linked ListWe 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 ADTtakes O(1) time
f
r
∅
nodes
elements
Linked Lists 9© 2004 Goodrich, Tamassia
Removing at the Tail
Removing at the tailof a singly linked listis not efficient!There is noconstant-time wayto update the tail topoint to the previousnode
Linked Lists 10© 2004 Goodrich, Tamassia
Doubly Linked ListA doubly linked list is a more complex type oflist that allows insertion in the middleNodes store:
element (sometimes combined into the nodeinstead of a reference)
link to the previous node link to the next node
Special trailer and header nodes
prev next
elem
trailerheader nodes/positions
elements
node
Linked Lists 11© 2004 Goodrich, Tamassia
InsertionWe visualize operation insertAfter(p, X), which returns position q
A B X C
A B C
p
A B C
p
X
q
p q