Upload
rajendranbehappy
View
8
Download
0
Embed Size (px)
DESCRIPTION
Single Linked List
Citation preview
jrfTypewritten textSingle Linked List
Singly Linked List
I A singly linked list provides an implementation of List ADT.
I Each node stores:I element (data)
I link to the next node node
next
element
I Variables first and optional last point to the first/last node.
I Optional variable size stores the size of the list.
first last
element 1 element 2 element 3 element 4
Singly Linked List: size
If we store the size on the variable size, then:size():
return sizeRunning time: O(1).
If we do not store the size on a variable, then:size():
s = 0m = firstwhile m != do
s = s + 1m = m.next
donereturn s
Running time: O(n).
Singly Linked List: insertAfter
insertAfter(n, o):x = new node with element ox.next = n.nextn.next = xif n == last then last = xsize = size + 1
A B C
A B C
o
n
n
x
last
last
first
first
Running time: O(1).
Singly Linked List: insertFirst
insertFirst(o):x = new node with element ox.next = firstfirst = xif last == then last = xsize = size + 1
A B C
A B Co
first
first, x
Running time: O(1).
Singly Linked List: insertBefore
insertBefore(n, o):if n == first then
insertFirst(o)else
m = firstwhile m.next != n do
m = m.nextdoneinsertAfter(m, o)
(error check m != has been left out for simplicity)
We need to find the node m before n:I requires a search through the list
Running time: O(n) where n the number of elements in the list.(worst case we have to search through the whole list)
Singly Linked List: Performance
Operation Worst case Complexitysize, isEmpty O(1) 1
first, last, after O(1) 2
before O(n)replaceElement, swapElements O(1)insertFirst, insertLast O(1) 2
insertAfter O(1)insertBefore O(n)remove O(n) 3
atRank, rankOf, elemAtRank O(n)replaceAtRank O(n)insertAtRank, removeAtRank O(n)
1 size needs O(n) if we do not store the size on a variable.2 last and insertLast need O(n) if we have no variable last.3 remove(n) runs in best case in O(1) if n == first.
Stack with a Singly Linked List
We can implement a stack with a singly linked list:I top element is stored at the first node
Each stack operation runs in O(1) time:
I push(o):insertFirst(o)
I pop():o = first().elementremove(first())return o
first (top)
element 1 element 2 element 3 element 4
Queue with a Singly Linked List
We can implement a queue with a singly linked list:I front element is stored at the first node
I rear element is stored at the last node
Each queue operation runs in O(1) time:
I enqueue(o):insertLast(o)
I dequeue():o = first().elementremove(first())return o
first (top) last (rear)
element 1 element 2 element 3 element 4