Linked List Operations
Linked List Operations
Linked List operations are as follows
- Traversal – Access the nodes of the list.
- Insertion – Adds a new element to an existing linked list.
- Deletion – deletets a node from an existing linked list.
- Search – search a particular element in the linked list
1. Traverse a Linked List
Traversing is a accessing the nodes of a linked list in order to process
Algorithm of traversing the linked list
Step 1: [INITIALIZE] SET PTR = HEAD Step 2: Repeat Steps 3 and 4 while PTR != NULL Step 3: Apply process to PTR -> DATA Step 4: SET PTR = PTR->NEXT [END OF LOOP] Step 5: EXIT
Program of traversing the linked list
struct node *temp = head; printf("\n\nList elements are - \n"); while(temp != NULL) { printf("%d --->",temp->data); temp = temp->next; }
Output
List elements are - 1 --->2 --->3 --->
2. Insert Elements to a Linked List
There are three cases to inserting element in linked list
- Insertion at the beginning
- Insertion at the end.
- Insertion after a given node
1. Insert at the beginning
- Allocate memory for new node and initialize it data
- Store data
- Change next element of new node to point to head
- Change the head to point to just created node
Block of code of insert at begining
struct node *newNode; newNode = malloc(sizeof(struct node)); newNode->data = 4; newNode->next = head; head = newNode;
2. Insert at the End
- Allocate memory for new node
- Store data
- Traverse to last node
- Change next of last node to just created node
Block of code of insert at end
struct node *newNode; newNode = malloc(sizeof(struct node)); newNode->data = 4; newNode->next = NULL; struct node *temp = head; while(temp->next != NULL){ temp = temp->next; } temp->next = newNode;
3. Insert at the given node
Allocate memory and store data for new node and traverse to node one before the required position of new node after that change next pointers to include new node in between
Block of code of insert at given node
struct node *newNode; newNode = malloc(sizeof(struct node)); newNode->data = 4; struct node *temp = head; for(int i=2; i < position; i++) { if(temp->next != NULL) { temp = temp->next; } } newNode->next = temp->next; temp->next = newNode;
3. Delete from a Linked List
1. Delete from beginning
Point head to the next node
head = head->next;
2. Delete from end
Traverse to second last element and change next pointer to null
struct node* temp = head; while(temp->next->next!=NULL){ temp = temp->next; } temp->next = NULL;
3. Delete from middle
Traverse to element before the element to be deleted and change next pointers to ecxcept the node from the chain
for(int i=2; i< position; i++) { if(temp->next!=NULL) { temp = temp->next; } } temp->next = temp->next->next;
Read more, Linked List Data Structure