Program to insert node at nth position in linked list
Write a function to insert a node at given position. Simple C Program to insert node at nth position.
C Program:
C Program:
#include<stdio.h> #include<stdlib.h> struct Node { int data; struct Node *next; }; struct Node *CreateNode(int n) { struct Node *newNode=(struct Node*)malloc(sizeof(struct Node)); newNode->data = n; newNode->next = NULL; return newNode; } int CountNodes(struct Node *head) { int count = 0; struct Node *curr = head; while(curr!=NULL) { count++; curr = curr->next; } return count; } struct Node *Insert(struct Node *head,int n,int k) { int i=1; struct Node *newNode = CreateNode(n); struct Node *temp = head; int count = CountNodes(head); /* If there is no node in linked list and we have to add node at position first */ if(head==NULL&&k==1) { head = newNode; return head; } if(count==k-1) { for(i=1;i<k-1;i++) { temp = temp->next; } newNode->next = temp->next; temp->next = newNode; return head; } else { printf("Insertion not possible\n"); return head; } } void PrintList(struct Node *head) { struct Node *curr = head; if(curr==NULL) { printf("List is empty"); } else { while(curr!=NULL) { printf("%d ",curr->data); curr = curr->next; } } printf("\n"); } int main() { struct Node *head = NULL; head = Insert(head,54,10); head = Insert(head,32,1); head = Insert(head,45,3); PrintList(head); head = Insert(head,58,6); PrintList(head); }