DS Lab · Experiment 1
Singly linked list operations
CLinked listsJNTUH R22 · CS306PC
Aim
To write a menu-driven C program that uses functions to create a singly linked list, insert a node at the beginning, at the end or at a given position, delete a node by position or by value, and traverse (display) the list.
Algorithm
- Define a node with two fields:
dataand a pointernextto the next node. Keep a pointerheadto the first node; an empty list hashead = NULL. - Create: read n values and add each one at the end of the list.
- Insert at beginning: make a new node, point its
nexttohead, and make it the newhead. - Insert at end: walk to the last node (the one whose
nextisNULL) and link the new node after it. - Insert at position p: if p is 1, insert at the beginning. Otherwise walk to node p − 1, set
new->next = temp->nextand thentemp->next = new. - Delete at position p or by value: find the node and the node before it, link the previous node to the node after it, and free the deleted node. Report an error if the list is empty or the node is not found.
- Traverse: start at
headand print each node's data untilNULL, counting the nodes. - Repeat the menu until the user chooses Exit, then free every node.
Program
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
/* Allocate a new node holding value */
struct node *create_node(int value) {
struct node *newnode = malloc(sizeof(struct node));
if (newnode == NULL) {
printf("Memory not available\n");
exit(1);
}
newnode->data = value;
newnode->next = NULL;
return newnode;
}
int count_nodes(struct node *head) {
int count = 0;
while (head != NULL) {
count++;
head = head->next;
}
return count;
}
void display(struct node *head) {
if (head == NULL) {
printf("List is empty\n");
return;
}
printf("List: ");
for (struct node *temp = head; temp != NULL; temp = temp->next) {
printf("%d -> ", temp->data);
}
printf("NULL\n");
}
struct node *insert_begin(struct node *head, int value) {
struct node *newnode = create_node(value);
newnode->next = head;
return newnode; /* new node is the new head */
}
struct node *insert_end(struct node *head, int value) {
struct node *newnode = create_node(value);
if (head == NULL) {
return newnode;
}
struct node *temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newnode;
return head;
}
struct node *insert_at(struct node *head, int value, int pos) {
if (pos < 1 || pos > count_nodes(head) + 1) {
printf("Invalid position\n");
return head;
}
if (pos == 1) {
return insert_begin(head, value);
}
struct node *temp = head;
for (int i = 1; i < pos - 1; i++) { /* stop at node pos-1 */
temp = temp->next;
}
struct node *newnode = create_node(value);
newnode->next = temp->next;
temp->next = newnode;
return head;
}
struct node *delete_at(struct node *head, int pos) {
if (pos < 1 || pos > count_nodes(head)) {
printf("Invalid position\n");
return head;
}
struct node *del;
if (pos == 1) {
del = head;
head = head->next;
} else {
struct node *temp = head;
for (int i = 1; i < pos - 1; i++) {
temp = temp->next;
}
del = temp->next;
temp->next = del->next;
}
printf("Deleted %d\n", del->data);
free(del);
return head;
}
struct node *delete_value(struct node *head, int value) {
struct node *temp = head, *prev = NULL;
while (temp != NULL && temp->data != value) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
printf("%d not found in the list\n", value);
return head;
}
if (prev == NULL) {
head = temp->next; /* deleting the first node */
} else {
prev->next = temp->next;
}
printf("Deleted %d\n", value);
free(temp);
return head;
}
void free_list(struct node *head) {
while (head != NULL) {
struct node *temp = head;
head = head->next;
free(temp);
}
}
int read_int(const char *prompt, int *x) {
printf("%s", prompt);
return scanf("%d", x) == 1;
}
struct node *create_list(struct node *head) {
int n, value;
free_list(head); /* start a fresh list */
head = NULL;
if (!read_int("Enter number of nodes: ", &n) || n < 1) {
printf("Invalid number of nodes\n");
return NULL;
}
printf("Enter %d values: ", n);
for (int i = 0; i < n; i++) {
if (scanf("%d", &value) != 1) {
printf("Invalid input\n");
break;
}
head = insert_end(head, value);
}
return head;
}
int main(void) {
struct node *head = NULL;
int choice, value, pos;
printf("SINGLY LINKED LIST\n");
printf("1. Create list\n2. Insert at beginning\n3. Insert at end\n");
printf("4. Insert at position\n5. Delete at position\n6. Delete by value\n");
printf("7. Display\n8. Exit\n");
do {
if (!read_int("\nEnter your choice: ", &choice)) {
printf("Invalid input\n");
break;
}
switch (choice) {
case 1:
head = create_list(head);
display(head);
break;
case 2:
if (read_int("Enter value: ", &value)) {
head = insert_begin(head, value);
display(head);
}
break;
case 3:
if (read_int("Enter value: ", &value)) {
head = insert_end(head, value);
display(head);
}
break;
case 4:
if (read_int("Enter value: ", &value) && read_int("Enter position: ", &pos)) {
head = insert_at(head, value, pos);
display(head);
}
break;
case 5:
if (head == NULL) {
printf("List is empty, nothing to delete\n");
} else if (read_int("Enter position: ", &pos)) {
head = delete_at(head, pos);
display(head);
}
break;
case 6:
if (head == NULL) {
printf("List is empty, nothing to delete\n");
} else if (read_int("Enter value to delete: ", &value)) {
head = delete_value(head, value);
display(head);
}
break;
case 7:
display(head);
printf("Number of nodes: %d\n", count_nodes(head));
break;
case 8:
break;
default:
printf("Invalid choice\n");
}
} while (choice != 8);
free_list(head);
printf("All nodes freed. Exiting.\n");
return 0;
}Output
SINGLY LINKED LIST
1. Create list
2. Insert at beginning
3. Insert at end
4. Insert at position
5. Delete at position
6. Delete by value
7. Display
8. Exit
Enter your choice: 5
List is empty, nothing to delete
Enter your choice: 1
Enter number of nodes: 3
Enter 3 values: 10 20 30
List: 10 -> 20 -> 30 -> NULL
Enter your choice: 2
Enter value: 5
List: 5 -> 10 -> 20 -> 30 -> NULL
Enter your choice: 3
Enter value: 40
List: 5 -> 10 -> 20 -> 30 -> 40 -> NULL
Enter your choice: 4
Enter value: 25
Enter position: 4
List: 5 -> 10 -> 20 -> 25 -> 30 -> 40 -> NULL
Enter your choice: 4
Enter value: 99
Enter position: 9
Invalid position
List: 5 -> 10 -> 20 -> 25 -> 30 -> 40 -> NULL
Enter your choice: 5
Enter position: 1
Deleted 5
List: 10 -> 20 -> 25 -> 30 -> 40 -> NULL
Enter your choice: 6
Enter value to delete: 30
Deleted 30
List: 10 -> 20 -> 25 -> 40 -> NULL
Enter your choice: 6
Enter value to delete: 99
99 not found in the list
List: 10 -> 20 -> 25 -> 40 -> NULL
Enter your choice: 7
List: 10 -> 20 -> 25 -> 40 -> NULL
Number of nodes: 4
Enter your choice: 8
All nodes freed. Exiting.Recorded by compiling and running this exact program. Typed input appears after each prompt.
How it works
Positions are counted from 1, so position 1 is the first node. A new node can go at any position from 1 to (number of nodes + 1); the last of these means "at the end".
Each insert and delete function returns the (possibly new) head, and main stores it back: head = insert_begin(head, value);. This is how the head changes when the first node is inserted or deleted.
The run tries to delete from an empty list first, then builds the list, inserts at all three places, gives a position that does not exist, deletes by position and by value, and looks for a value that is not in the list.
Common mistakes
Losing the rest of the list during insertion by writing
temp->next = newnode;beforenewnode->next = temp->next;. Always link the new node to the rest of the list first.Changing
headinside a function and not returning it (or not passing&head). The change is lost when the function returns, so inserting at the beginning seems to do nothing.Using a node after calling
freeon it, for examplefree(temp); temp = temp->next;. Save the next pointer before freeing.Not checking for an empty list before deleting, which dereferences a
NULLpointer and crashes the program.
Viva questions
Try to answer each one aloud before you open it.
What is a singly linked list?
It is a chain of nodes where each node holds data and a pointer to the next node. The last node's pointer is
NULL, and the list is reached through a pointer to the first node, called the head.What are the advantages of a linked list over an array?
Its size can grow and shrink while the program runs, and inserting or deleting a node needs only pointer changes, not shifting of elements. An array has a fixed size and needs shifting.
What are its disadvantages?
There is no direct access by index, so reaching the k-th node takes k steps. Each node also needs extra memory for the pointer.
What is the time complexity of inserting at the beginning and at the end?
Inserting at the beginning is O(1). Inserting at the end is O(n) because we walk to the last node, unless we also keep a tail pointer.
Why is malloc used here, and what happens if we do not call free?
mallocgets memory for each node at run time from the heap. If nodes are not freed, that memory is not returned until the program ends, which is called a memory leak.
Learn the concepts
- Singly Linked Lists in Python: Build One From Scratch
- Linked Lists in C: Insert, Delete, Search, Reverse and Free
- Dynamic Memory Allocation in C: malloc, calloc, realloc and free
- Structures in C: struct, typedef, Arrays of Structs and Pointers to Structs
- Pointers in C: Addresses, the & and * Operators, and NULL