/* http://native-code.blogspot.com */ #include<stdio.h> #include<conio.h> #include<malloc.h> typedef struct link { int data; struct link *next; }node; node *ins_beg(node*, int); node *ins_aft_node(node*, int k, int n); void display(node*); void main() { int n,k,ch; node *head=NULL; while(1) { printf("/* http://native-code.blogspot.com */"); printf("\n\n1-->Insert at begining\n2-->Insert after given node\n3-->Display\n4-->EXIT\n"); scanf("%d",&ch); switch(ch) { case 2: printf("Enter value for new node:\n"); scanf("%d",&n); printf("Enter value at node after which to insert:\n"); scanf("%d",&k); head=ins_aft_node(head,k,n); break; case 3: display(head); printf("\n"); break; case 4: exit(0); case 1: printf("Enter value for new node:\n"); scanf("%d",&n); head=ins_beg(head,n); break; default: printf("Wrong choice.\n"); } } getch(); } node* ins_beg(node *h, int n) { node *temp, *r=h; temp=(node *)malloc(sizeof(node)); temp->data=n; temp->next=NULL; if(h==NULL) { h=temp; } else { temp->next=h; h=temp; } return(h); } node *ins_aft_node(node *h,int k,int n) { node *temp,*p,*l; temp=p=l=NULL; temp=(node *)malloc(sizeof(node)); temp->data=n; temp->next=NULL; p=h; while(p->data!=k) p=p->next; l=p->next; p->next = temp; temp->next=l; return(h); } void display(node *h) { node *r=h; while(r!=NULL) { printf("%d-->",r->data); r=r->next; } printf("NULL"); } /* http://native-code.blogspot.com */
Home
» C
» data-structure
» single-linked-list
» How to insert a new node at the after specified node of a single link list?
Post a Comment