By Arjun Tyagi
In this project, we will discuss how to delete a node from a singly linked list using C language. To delete a node at the nth position we have to traverse up to the nth element from starting.
To delete a node from a singly linked list we have to traverse through the list up to nth element. So, the time complexity to delete a node is big-oh(n) or O(n).
#include #include struct node{ int data; struct node* next; }; //declaring a node data-type// struct node* head; void delete(int pos){ struct node* prev; struct node* curr; struct node* after; curr=head; for(int i=0;i<pos-1;i++){ // Traversing up to the given position// prev=curr; curr=curr->next; } after=curr->next; prev->next=after; } void insertion(int data){ struct node* newnode=(struct node*) malloc(sizeof(struct node)); //allocating memory for a node// newnode->data=data; newnode->next=NULL; if(head==NULL){ //list is empty // head=newnode; } else{ struct node* temp=head; while(temp->next!=NULL){ temp=temp->next; //traversing to the last element// } temp->next=newnode; //Storing the address of new node in previous node link part// } } void print(){ struct node* temp=head; while(temp!=NULL){ if(temp->next==NULL) printf("%d",temp->data); else printf("%d->",temp->data); temp=temp->next; } printf("\n"); } int main() { insertion(1); insertion(2); insertion(3); insertion(4); print(); delete(2); print(); // your code goes here return 0; }
OUTPUT:
Image output:
Submitted by Arjun Tyagi (Arjuntyagi)
Download packets of source code on Coders Packet
Comments