Linked Lists-2
Linked Lists-2
A linked list is a linear data structure where elements, called nodes, are not stored in contiguous
memory locations. Instead, each node points to the next node in the sequence using a pointer.
The last node’s pointer is set to NULL, indicating the end of the list.
Node Structure in C
struct Node {
int data; // Stores the data of the node
struct Node* next; // Pointer to the next node in the list
};
Linked lists rely on dynamic memory allocation, typically using malloc() to allocate memory
for new nodes. After allocating memory, free() is used to release it when no longer needed.
int main() {
struct Node* head = createNode(10);
head->next = createNode(20);
head->next->next = createNode(30);
Tasks
★ Modify the code to create a linked list with 5 nodes (values: 1, 2, 3, 4, 5).
★ Write a function int length(struct Node* head) that returns the length of the
linked list.
Inserting Nodes
Insertion Operations
Tasks
Deleting Nodes
Deletion Operations
● Deleting the first node: Set the head to the second node and free the original head.
● Deleting the last node: Traverse to the second-last node, set its next to NULL, and
free the last node.
● Deleting a node at a given position: Adjust pointers to bypass the node to be deleted,
then free it.
Task
Task
★ Modify the code to find the kth occurrence of the search key.
★ Find the data of the kth node from the end/tail of the linked list.
Task
Loop Detection
Floyd’s Cycle-Finding Algorithm (Tortoise and Hare) is used to detect loops in linked lists.
if (slow == fast) {
return 1; // Loop detected
}
}
return 0; // No loop
}
Task
★ Create a loop in the list and test the loop detection function.
★ Remove the loop from the list.
Doubly Linked List
A doubly linked list has nodes with two pointers: one pointing to the next node and one to the
previous node.
struct DNode {
int data;
struct DNode* prev;
struct DNode* next;
};
if (head == NULL) {
newNode->prev = NULL;
head = newNode;
return;
}
Task
Tasks
★ Create a circular linked list and insert nodes at different positions. Traverse and print the
list.
★ Modify the circular linked list to handle insertion and deletion at any position.
Homework Tasks