Beruflich Dokumente
Kultur Dokumente
h>
#include<conio.h>
typedef struct list
{
int data;
struct list * next;
}list;
void init(list **h)
{
*h = NULL;
}
void create(list **h)//sorts and creates node
{
list *temp, *i;
temp = (list *) malloc(sizeof(list));
if(*h == NULL)//to make temp the first node
{
if(temp != NULL) // malloc is successfull
{
printf("\nEnter Data For First Node ");
scanf("%d", &temp->data);
temp->next = temp;
*h = temp;
}
else
printf("\nMemory Allocation Failed ");
}
else //to make temp successor nodes
{
if(temp != NULL)
{
printf("\nEnter Value For Node ");
scanf("%d", &temp->data);
i = *h;
if(temp->data < (*h)->data)// when new node is less than
first node
{
temp->next = *h;
*h = temp;
//traverse to last node of list so
//that we change its next to new head node
//and list remains circular
for(i = (*h)->next; i->next!= (*h)->next; i = i-
>next);
i->next = *h;
}
else// when new node is greater than or equal to first n
ode
{
for(i = *h; temp->data >= i->next->data && i-
>next!=*h; i= i->next);
if(i->next == *h ) //add at end
{
i->next = temp;
temp->next = *h;
}
else
{
temp->next = i->next ;
i->next = temp;
}
}
}
else
printf("\nMemory Allocation Failed ");
}
}
void disp(list *h)
{
list *temp;
temp = h;
do
{
printf("\n%d", temp->data);
temp = temp->next;
}while(temp != h);
}
void freelist(list **head)
{
list *temp, *temp1 = *head;
do
{
temp = *head;
*head = (*head)->next;
free(temp);
}while(*head != temp1);
*head = NULL;
}
void main()
{
int ch;
list *head1, *head2, *head3;
init(&head1);
init(&head2);
init(&head3);
clrscr();
do
{
printf("\nTo Create list1:1");
printf("\nTo display list1 :2");
printf("\nTo Create list2:3");
printf("\nTo display list2 :4");
printf("\nUnion of list1 and list2 : 5");
printf("\nTo display list3 :6");
printf("\nTo Exit :7\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
create(&head1);
break;
case 2:
disp(head1);
break;
case 3:
create(&head2);
break;
case 4:
disp(head2);
break;
case 5:
freelist(&head3);
head3 = uni(head1,head2);
disp(head3);
}
}while(ch!=6);
}