DSA521S-Linked List 3
DSA521S-Linked List 3
Algorithms 1
Linked List
2023
Objectives
At the end of the lesson, students should be able to carry out basic
operations such as:
Inserting a node at beginning of list, at position x, at the end of list!
Deleting a node; from beginning of list, at position x, at the end of list!
Traversing the list!
Finding a node x from list!(In-class activity)
WHY linked List if we can easily use arrays??
Node
Data Address
Types of linked lists
Singly linked list
Doubly linked list
Circular linked list
Doubly Circular linked list
Singly Linked List
A singly linked list is a linked list which can be traversed in only one
direction (forward traversal only). For example; from head to tail only, not
vice versa. It is the most widely used linked list. A singly linked list can be
illustrated as follows:
Head Pointer Head Node Tail
Head Node
Head Pointer
300 5 200 100 2 300 200 8 100
100
Head Pointer
newNode = 400
newNode = 400
i=1
Now we have created three insert operations of the linked list. It is more
efficient to create three functions, one for inserting a node at the
beginning, another for inserting a node at the end and another function for
inserting a node at a given position, and then call those functions in the
main function.
Let’s write a simple pseudocode to delete data in the linked list based
on the diagram above.
A node is deleted when it is disconnected from other nodes, but even
if it is disconnected from others, we still need to free the memory
allocated to that node, because it is still holding some data. Freeing
the memory allocated to the node means completely deleting that
node.
Let’s delete data from the list using the pseudocode below. We are
going to use functions in this examples.
1. Deleting a node at the beginning of list
To delete a node at the beginning of the list, we update the value of
the head to point to the second node in the list. Let’s look at the
pseudocode below.
deleteAtBeg(){
IF(head == NULL)THEN
DISPLAY “List is empty!”
ELSE
temp = head //pointing temp to first node
head = head -> next //pointing head to second node
temp = free //deleting first node by freeing it or use free(temp)
function
ENDIF
}
deleteAtGivenPos(){
temp = head
DISPLAY “Enter position where you want to delete” //prompt
GET position //get position to delete
WHILE(i < position - 1) //traverse the list until third node-1
temp = temp -> next //move temp pointer
i = i + 1 //increment i
ENDWHILE
nextNode = temp -> next //assign address of third node to nextNode
temp -> next = nextNode -> next //assign address of last node to
second node
nextNode = free //completely delete node (free(nextNode))
}