Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- struct linked_list
- {
- int data;
- struct linked_list *next;
- };
- typedef struct linked_list *node;
- node head=NULL;
- node createnode()
- {
- node temp;
- temp=(node)malloc(sizeof(node));
- temp->next=NULL;
- return temp;
- }
- void insertion_sort(int value)
- {
- node temp=createnode(),p=head,prev=NULL;
- temp->data=value;
- if(p==NULL)
- {
- p=temp;
- head=p;
- return ;
- }
- else if(value>p->data)
- {
- temp->next=p;
- head=temp;
- return ;
- }
- else if(value<p->data && p->next==NULL)
- {
- head->next=temp;
- return ;
- }
- else
- {
- while(p->next!=NULL)
- {
- if(p->data>value)
- {
- prev=p;
- p=p->next;
- continue;
- }
- else
- {
- temp->next=p;
- prev->next=temp;
- return ;
- }
- }
- if(p->data < value )
- {
- temp->next=p;
- prev->next=temp;
- return ;
- }
- else
- {
- p->next=temp;
- return ;
- }
- }
- }
- void print_node()
- {
- node a;
- if(head==NULL)
- printf("empty\n");
- else
- {
- a=head;
- while(a!=NULL)
- {
- printf("%d ",a->data);
- a=a->next;
- }
- }
- printf("\n");
- }
- int main()
- {
- int n,data;
- node head=NULL;
- printf("1. add element\n2. print sorted\n3. exit\n");
- while(1)
- {
- scanf("%d",&n);
- if(n==1)
- {
- printf("new data: ");
- scanf("%d",&data);
- insertion_sort(data);
- }
- else if(n==2)
- {
- print_node();
- }
- else
- return 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement