hello everyone, i have a problem in blew program,i dont know how to get the union set without changing the head1. i want to put the union set in the head3.
Code:
/************************************************************************/
/* Get the Union Set in Single Link List */
/************************************************************************/
#include <stdio.h>
#include <stdlib.h>
typedef struct _tagLinkNode
{
int data;
struct _tagLinkNode *next;
}LinkNode;
LinkNode* CreateList(LinkNode *head)
{
head = (LinkNode *)malloc(sizeof(LinkNode));
if (NULL == head)
{
printf("malloc error\n");
return;
}
head->data = 0;
head->next = NULL;
return head;
}
void InputData(LinkNode *head)
{
LinkNode *p = NULL;
LinkNode *pNode = NULL;
int data = 0;
p = head;
scanf("%d", &data);
while(-1 != data)
{
pNode = (LinkNode *)malloc(sizeof(LinkNode));
if (NULL == pNode)
{
printf("malloc error\n");
return;
}
if (-1 != data)
{
pNode->data = data;
pNode->next = NULL;
p->next = pNode;
p = pNode;
}
scanf("%d", &data);
}
}
void OutPutData(LinkNode *pHead)
{
LinkNode *p = pHead;
if (NULL != p)
{
p = p->next;
}
while (NULL != p)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
LinkNode** GetUnion(LinkNode *head1, LinkNode *head2, LinkNode **head3)
{
LinkNode *p1 = head1;
LinkNode *p2 = head2;
LinkNode *p3 = NULL;
LinkNode *p3pre = NULL;
if (NULL == p1 && NULL == p2)
{
return;
}
head3 = (LinkNode **)malloc(sizeof(LinkNode));
*head3 = (LinkNode *)malloc(sizeof(LinkNode));
if (NULL == *head3 || NULL == head3)
{
printf("malloc error\n");
return NULL;
}
(*head3)->data = 0;
(*head3)->next = NULL;
p1 = p1->next;
p2 = p2->next;
p3 = *head3 = head1;
p3 = p3->next;
while (NULL != p2)
{
p3pre = *head3;
p3 = p3pre->next;
while (NULL != p3)
{
if (p2->data == p3->data)
{
break;
}
p3pre = p3pre->next;
p3 = p3->next;
}
if (NULL == p3)
{
p3pre->next = p2;
p3pre = p3pre->next;
}
p2 = p2->next;
}
return head3;
}
int main()
{
LinkNode *list1 = NULL;
LinkNode *list2 = NULL;
LinkNode **list3 = NULL;
list1 = CreateList(list1);
printf("please input single link list1(-1 end): ");
InputData(list1);
list2 = CreateList(list2);
printf("please input single link list2(-1 end): ");
InputData(list2);
printf("\n\nThe Set 1: ");
OutPutData(list1);
printf("The Set2: ");
OutPutData(list2);
//list3 = CreateList(list3);
printf("The Union Set is :");
list3 = GetUnion(list1, list2, list3);
OutPutData(*list3);
return 0;
}