合并2个链表中的数据,求帮忙
#include <stdio.h>
#include<malloc.h>
#define null 0
typedef struct node
{
int data;
struct node *next;
}NODE; //定义结构体
NODE *Create()
//用尾插法建立带头节点的单链表
{
NODE *p,*head;
int x;
head=(NODE *)malloc(sizeof(NODE));
head->next=NULL;
printf("Input data,-1 to End!\n");
scanf("%d",&x);
while(x!=-1){
p=(NODE *)malloc(sizeof(NODE));
p->data=x;
p->next=head->next;
head->next=p;
scanf("%d",&x);
}
return(head);
}
NODE *Create1()
//用尾插法建立带头节点的单链表
{
NODE *p,*head;
int x;
head=(NODE *)malloc(sizeof(NODE));
head->next=NULL;
printf("Input data,-1 to End!\n");
scanf("%d",&x);
while(x!=-1){
p=(NODE *)malloc(sizeof(NODE));
p->data=x;
p->next=head->next;
head->next=p;
scanf("%d",&x);
}
return(head);
}
void hebing(NODE *head1,NODE *head2)
{
}
void main()
{
NODE *head1,*head2;
head1=Create();
head2=Create1();
hebing(head1,head2);
}
[解决办法]
#include <stdio.h>
#include <malloc.h>
#include <WINDOWS.H>
#define null 0
typedef struct node
{
int data;
struct node *next;
}NODE; //定义结构体
NODE *Create()
{
NODE *p,*head;
int x;
head=(NODE *)malloc(sizeof(NODE));
head->next=NULL;
printf("Input data,-1 to End!\n");
scanf("%d",&x);
while(x!=-1){
p=(NODE *)malloc(sizeof(NODE));
p->data=x;
p->next=head->next;
head->next=p;
scanf("%d",&x);
}
return(head);
}
NODE *Create1()
{
NODE *p,*head;
int x;
head=(NODE *)malloc(sizeof(NODE));
head->next=NULL;
printf("Input data,-1 to End!\n");
scanf("%d",&x);
while(x!=-1){
p=(NODE *)malloc(sizeof(NODE));
p->data=x;
p->next=head->next;
head->next=p;
scanf("%d",&x);
}
return(head);
}
//判断是否重覆
bool IsRepeatValue(NODE *p,NODE *tail,NODE *head)
{
bool bRet=false;
while(tail!=head)
{
if (p->data==tail->data)
{
bRet=true;
break;
}
tail=tail->next;
}
if (p->data==head->data)
{
bRet=true;
}
return bRet;
}
//head2追加到head1后面
void hebing(NODE *head1,NODE *head2)
{
NODE *Tail2;
Tail2=head2->next;
free(head2);
head2=Tail2;
while(head2->next)
{
head2=head2->next;
}
NODE *tmp=head1->next;
free(head1);
head1=tmp;
while(head1)
{
if(IsRepeatValue(head1,Tail2,head2))
{
tmp=head1->next;
free(head1);
head1=tmp;
continue;
}
head2->next=head1;
head2=head2->next;
head1=head1->next;
}
}
void main()
{
NODE *head1,*head2;
head1=Create();
head2=Create1();
hebing(head1,head2);
}
//假设head1和head2各自内部没有重复的。
void hebing(NODE * head1, NODE * head2){
//firstAdd和ptr1_origin_head是防止把head2的数据放到head1里之后,又把这些数据和head2里的进行比较。
bool firstAdd = true;
NODE * ptr1_origin_head = head1;
NODE * ptr1 = ptr1_origin_head;
NODE * ptr2 = head2;
while(ptr2->next != 0){
while(ptr1->next != 0){
if(ptr1->next->data == ptr2->next->data){//找到了
head2->next = head2->next->next;
free(ptr2->next);
ptr2 = head2;
break;
}else{
ptr1 = ptr1->next;
}
}
if(ptr1->next == 0){//找不到
NODE * ptmp = head1->next;
head1->next = head2->next;
head2->next = head2->next->next;
head1->next->next = ptmp;
if(firstAdd){
ptr1_origin_head = head1->next;
firstAdd = false;
}
}
ptr1 = ptr1_origin_head;
ptr2 = head2;
}
free(head2);
}