Question:
How can a node be inserted in the middle of a linked list?
Answer:
By repointing the previous and the next elements of existing nodes to the new node. You can insert a node in the middle of a linked list by repointing the previous and the next elements of existing nodes to the new node. Source: CoolInterview.com
struct linklist { int roll; struct linklist *next; }; typedef struct linklist sl; sl *head; void create() { sl *p,*q; p=(sl*)malloc(sizeof(sl)); printf("enter the roll no:=>"); scanf("%d",&p->roll); if(head==NULL) { head=p; } else { q=head; while(q->next!=NULL) { q=q->next; } q->next=p; } } void insert_middle() { int n=0,ch; sl *p,*q; p=(sl*)malloc(sizeof(sl)); printf("enter the roll no:=>"); scanf("%d",&p->roll); p->next=NULL; printf("enter the no of node for after insert"); scanf("%d",&n); q=head; while(q!=NULL) { c++; if(n==c) { p->next=q->next; q->next=p; break; } q=q->next; } Source: CoolInterview.com
Answered by: ansar husain | Date: 4/16/2010
| Contact ansar husain
struct linjlist { int roll; struct linklist *next; }; typedef struct linklist ls; ls *head; void midlde() { int n,c=0; ls *p,*q; printf("enter the bvalue for after node insert"); scanf("%d",&n); p=(ls*)malloc(sizeof(ls)); printf("enter the rol no:=>"); scanf("%d",&p->roll); p->next=NULL; q=head; while(q!=NULL) { c++; if(c==n) { p->next=q->next; q-next=p; break; } q=q->next; } } Source: CoolInterview.com
Answered by: ansar husain | Date: 4/28/2010
| Contact ansar husain
If you have the better answer, then send it to us. We will display your answer after the approval.
Rules to Post Answers in CoolInterview.com:-
- There should not be any Spelling Mistakes.
- There should not be any Gramatical Errors.
- Answers must not contain any bad words.
- Answers should not be the repeat of same answer, already approved.
- Answer should be complete in itself.
|