Singly Linked List
Singly Linked List
struct Node {
int data;
};
temp->data = data;
temp->next = NULL;
return temp;
}
Traversal of Singly Linked List
Traversal involves visiting each node in the linked list and performing some operation on the
data. A simple traversal function would print or process the data of each node.
Step-by-step approach:
Use a while loop to iterate through the list until the current pointer reaches NULL.
Inside the loop, print the data of the current node and move the current pointer to the next
node.
printf("\n");
}
Implementation of Singly Linked List in C
A singly linked list is a type of linked list where only the address of the next node is stored in the
current node along with the data field and the last node in the list contains NULL pointer. This
makes it impossible to find the address of the particular node in the list without accessing the
node previous to it. So we can only access the data sequentially in the node.
// Function to insert a new element at the beginning of the singly linked list
void insertAtFirst(struct Node** head, int data) {
struct Node* newNode = createNode(data);
newNode->next = *head;
*head = newNode;
}
// Function to insert a new element at the end of the singly linked list
void insertAtEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
// Function to insert a new element at a specific position in the singly linked list
void insertAtPosition(struct Node** head, int data, int position) {
struct Node* newNode = createNode(data);
if (position == 0) {
insertAtFirst(head,data);
return;
}
struct Node* temp = *head;
for (int i = 0; temp != NULL && i < position - 1; i++) {
temp = temp->next;
}
if (temp == NULL) {
printf("Position out of range\n");
free(newNode);
return;
}
newNode->next = temp->next;
temp->next = newNode;
}
// Driver Code
int main() {
struct Node* head = NULL;
insertAtFirst(&head, 10);
printf("Linked list after inserting the node:10 at the beginning \n");
print(head);
return 0;
}