Problem statement: Given a position, delete the number at that position in the linked list.
Iterative Solution 1) Find the previous position that is to be deleted by traversing till the position. 2) Assign the next of the previous node. 3) Free(temp). |
Here we should keep in mind that the position given should be less than the length of the linked list.
As linked list starting position or index is 0. The position can be greater than or equal to 0 and less than the length of the LinkedList.
Constraints position < length of LinkedList 0 <= position < length of LinkedList |
/*C code to delete an node at a position from the Linked List */ #include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node *next; } NODE; NODE *head = NULL; NODE *newNode(int key) { NODE *temp = (NODE *)malloc(sizeof(NODE)); temp->data = key; temp->next = NULL; return temp; } int count(NODE *head) { NODE *temp = head; if (temp == NULL) { return 0; } int count = 0; while (temp != NULL) { count++; temp = temp->next; } return count; } NODE *deleteNode(NODE *head, int pos, int len) { NODE *temp = head, *prev; if (pos == 0) { head = temp->next; return head; } if (pos > len) { printf("Position=%d should be less than length=%d of linkedlist!\n", pos, len); return head; } for (int i = 0; i < pos; i++) { prev = temp; temp = temp->next; } prev->next = temp->next; printf("Node from %d position is deleted!\n", pos); free(temp); return head; } void printList() { NODE *temp = head; if (temp == NULL) { printf("List is empty!\n"); return; } printf("Linked List is\t"); while (temp != NULL) { printf("%d--> ", temp->data); temp = temp->next; } printf("NULL\n"); } int main() { head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = NULL; printList(); int pos = 0; int lengthOfLL = count(head); printf("Enter the position to delete\t"); scanf("%d", &pos); head = deleteNode(head, pos, lengthOfLL); printList(); return 0; }
$ gcc delete_node.c $ ./a.out Linked List is 1–> 2–> 3–> 4–> NULL Enter the position to delete 8 Position=8 should be less than length=4 of linkedlist! Linked List is 1–> 2–> 3–> 4–> NULL $ ./a.out Linked List is 1–> 2–> 3–> 4–> NULL Enter the position to delete 2 Node from 2 position is deleted! Linked List is 1–> 2–> 4–> NULL $ ./a.out Linked List is 1–> 2–> 3–> 4–> NULL Enter the position to delete 3 Node from 3 position is deleted! Linked List is 1–> 2–> 3–> NULL $ ./a.out Linked List is 1–> 2–> 3–> 4–> NULL Enter the position to delete 2 Node from 2 position is deleted! Linked List is 1–> 2–> 4–> NULL $ ./a.out Linked List is 1–> 2–> 3–> 4–> NULL Enter the position to delete 0 Linked List is 2–> 3–> 4–> NULL $ |
also see
C Programming language |
Go Programming language |
Linked List | Array |
Stack | Queue |
Puzzle | Reasoning |
Aptitude | HTML |