Before seeing the solution make sure that you tried enough. Don’t paste the whole code, just find out the logic. If you stuck in trouble, just inform me on comment.
/**Bismillahir Rahmanir Rahim.**/ #include <stdio.h> #include <stdlib.h> int m=1, i, x, n, nth, y; struct node { int info; struct node* ptr; }; struct node* start; struct node* temp1; struct node* temp2; void insert(int x) { temp1 = (struct node*) malloc(sizeof(struct node)); temp1->info = x; temp1->ptr = NULL; if(m==1) { temp1->ptr = NULL; start = temp1; temp2 = temp1; m = 0; return ; } temp2->ptr = temp1; temp2 = temp1; } int find_position(int x) { temp1 = start; for(i=1; temp1!=NULL; i++) { if(temp1->info >= x) return i; temp1 = temp1->ptr; } return i; } void insert_first(int x) { temp1 = (struct node*) malloc(sizeof(struct node)); temp1->info = x; temp1->ptr = start; start = temp1; } void insert_nth(int nth, int x) { if(nth==1) { insert_first(x); return; } temp1 = (struct node*) malloc(sizeof(struct node)); temp1->info = x; temp2 = start; for(i=0; i<nth-2; i++) temp2 = temp2->ptr; temp1->ptr = temp2->ptr; temp2->ptr = temp1; } void print() { temp1 = start; printf("List is: "); while(temp1 != NULL) { printf(" %d ", temp1->info); temp1 = temp1->ptr; } printf("\n"); free(temp1); } int main() { start = NULL; printf("How Many Node??\n"); scanf("%d", &n); printf("Print %d node :: \n", n); for(i=0; i<n; i++) { scanf("%d", &x); insert(x); } printf("What you want to Insert....\n"); scanf("%d", &x); y = find_position(x); /**PROCEDURE 5.6**/ insert_nth(y, x); print(); free(temp1); return 0; }
First Input n = number of Total Node. ex. 4.
second Input n node item . ex. 10 30 40 50.
What I want to insert. ex. 20.
Sample Input:
------------------
4
10 30 40 50
20
sample Output:
---------------------
List is : 10 20 30 40 50
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.