Professional Documents
Culture Documents
Start
a
Each node contains a value
and a link (pointer or reference) to some other node The last node contains a null link The list may (or may not) have a header
2
Singly-linked lists
Here is a singly-linked list (SLL):
start a b c d
last node has no successor) The header points to the first node in the list (or contains the null link if the list is empty)
Operation
4
1)
2) 3)
Traversing
Insertion Deletion
4)
Searching
Traversing (algorithm)
5
1) ptr=start 2) If(start==null) 2a) write(sorry list is empty) 2b) exit 3)while(ptr=null) { Write(ptr->data) Ptr->ptr->link }
Ptr
start
head one two
null
ptr
start
one two three
Insertion at start(algorithm)
7
Info link
null
start
head one two
null
Info link
null
start
head one
ptr
two
null
Info link
start
head
ptr two
null
deletion at start(algorithm)
10
start
head one two
null
deletion at end(algorithm)
1) if(start==null) { Write nathing to delete exit } 2) ptr=start, save=start 3) while(ptr->link!=null) { Ptr=ptr->link } 4) If(save==ptr) { Start=null } 5)While(save->link!=ptr) { Save=save->link } 6) Save->link=null
11
start
head
save one
ptr two
null
deletion at mid(algorithm)
1) if(start==null) { Write nathing to delete exit } 2) ptr=start, save=start 3) while(ptr->data!=x) { Ptr=ptr->link } 5)While(save->link!=ptr) { Save=save->link } 6) Save->link=ptr->link
12
save
ptr
start
head one two
null
searching(algorithm)
1) if(start==null) { Write list is empty exit } 2) ptr=start 3) while(ptr->data!=x && ptr!=null) { Ptr=ptr->link } 5) if(ptr==null) write data not found Else write found
13
start
head one two
null
Each node points to not only successor but the predecessor There are two NULL: at the first and last nodes in the list Advantage: given a node, it is easy to visit its predecessor. Convenient to traverse lists backwards
Head
A Head
How do we know when we have finished traversing the list? (Tip: check if the pointer of the current node is equal to the head.)
Disadvantages:
Can be traversed in either direction (may be essential for some programs) Some operations, such as deletion and inserting before a node, become easier
Requires more space List manipulations are slower (because more links must be changed) Greater chance of having bugs (because more links must be manipulated)
16
17
Thanks