Welcome to our deep dive into C Singly Linked Lists! In this lesson, we'll explore what a Singly Linked List is, why we use them, and how to create and manipulate them in C. Let's get started!
A Singly Linked List is a linear data structure made up of nodes where each node contains data and a reference to the next node in the list. Each node in a Singly Linked List only points to the next node, not the previous one.
š” Pro Tip:
To create a Singly Linked List in C, we first need to define a structure for a Node, which will contain data and a pointer to the next Node.
struct Node {
int data;
struct Node* next;
};Here, struct Node is a user-defined data type. Inside this structure, data stores the value of the current node, and next is a pointer to the next node in the list.
Now that we have the Node structure, let's create a Singly Linked List. We'll start by initializing the head of the list as NULL, indicating an empty list.
struct Node* head = NULL;To add nodes to the list, we'll create a function called insertNode(). This function will create a new Node, set its data to the provided value, and make it the head of the list or append it to the end of the existing list.
void insertNode(int data) {
struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
} else {
struct Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}š” Pro Tip:
malloc() to dynamically allocate memory for new nodes.Removing a node from a Singly Linked List involves finding the node to be deleted and changing the pointer of the previous node to skip the removed node. We'll create a function called deleteNode() for this purpose.
void deleteNode(int key) {
if (head == NULL) {
printf("List is empty.\n");
return;
}
if (head->data == key) {
struct Node* temp = head;
head = head->next;
free(temp);
return;
}
struct Node* current = head;
while (current->next != NULL && current->next->data != key) {
current = current->next;
}
if (current->next == NULL) {
printf("Element not found.\n");
return;
}
struct Node* temp = current->next;
current->next = current->next->next;
free(temp);
}š” Pro Tip:
What is the data type of a Singly Linked List in C?
Now that you have a grasp of Singly Linked Lists, practice by implementing the complete implementation of inserting, deleting, and displaying nodes in a Singly Linked List. Good luck, and happy coding! š