Linked list algorithms
Linked list algorithms
Let us create a linked list, using the above algorithm, having data 10, 15, 20 and 12:
After the first node is created, the linked list looks like:
10
head prt
After the second node is created, the linked list looks like:
10 15
head prt
After the third node is created, the linked list looks like:
10 15 20
head ptr
After the fourth node is created, the linked list looks like:
10 15 20 12
head ptr
1: begin
2: create newNode
3: newNode->data ← num
4: newNode->next ← NULL
5: ptr ← head
/* make ptr to point to last node */
6: repeat step 7
7: ptr ← ptr->next
8: until ptr->next != NULL
9: ptr->next ← newNode
10: end
head newNode
10 15 20 12 7
10 15 20 12 7
1: begin
2: create newNode
3: newNode->data ← num
/* points to the previous first node */
4: newNode->next ← head
5: head ← newNode /*updating the head */
6: end
1: begin
2: check underflow condition
3: ptr ← head
/* updates head to the new first node */
4: head ← ptr->next
5: free ptr /*deallocating the head */
6: end
10 15 20 12 7
head
10 15 20 12 7
head ptr
10 15 20 12 7
ptr head
15 20 12 7
head
1: begin
2: check underflow condition
3: ptr ← head
4: repeat steps 5, 6
5: preptr ← ptr
6: ptr ← ptr->next
7: until ptr->next != NULL
8: preptr->next ← NULL
9: free ptr /*deallocating the ptr */
10: end
1: begin
2: check underflow condition
3: ptr ← head
4: repeat steps 5, 6
5: preptr ← ptr
6: ptr ← ptr->next
7: until preptr->data != value
8: preptr->next ← ptr->next
9: free ptr /* deallocating the ptr */
10: end
head
To delete node with value 12, the (logical) steps are as follows:
10 15 20 12 7
head
10 15 20 12 7
head
10 15 20 12 7
head
1: begin
2: check underflow condition
3: ptr ← head
4: preptr ← head
5: repeat steps 6, 7
6: preptr ← ptr
7: ptr ← ptr->next
8: until ptr->data != value
9: preptr->next ← ptr->next
10: free ptr /* deallocating the ptr */
11: end