一段已经十分完善的代码,从生成到显示都已经有了:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct Node
{
int data;
Node* next;
}*LNode;
void Add(LNode &link, int e)
{
LNode p = link;
LNode q = (LNode)malloc(sizeof(Node));
q->next = NULL;
LNode s = link->next;
q->data = e;
while(s)
{
if(s->data>=e)break;
p = p->next;
s = s->next;
}
q->next = s;
p->next = q;
}
void Merge(LNode &A, LNode &B, LNode &C)
{
LNode p = A->next;
LNode t = A;
LNode q = B->next;
LNode k = B;
LNode s = C;
LNode m = NULL;
while(p&&q)
{
while(p->next)
{
t = t->next;
p = p->next;
}
while(q->next)
{
k = k->next;
q = q->next;
}
if(p->data>q->data)
{
if(s->next == NULL)
s->next = p;
else m = p;
t->next = NULL;
}
if(p->data == q->data)
{
m = p;
k->next = NULL;
free(q);
}
if(p->data<q->data)
{
if(s->next == NULL)
s->next = q;
else m = q;
k->next = NULL;
}
if(m!=NULL)
{
if(m->data == s->data)
free(m);
else s->next = m;
}
p = A->next;
t = A;
q = B->next;
k = B;
s = s->next;
}
p = A->next;
t = A;
q = B->next;
k = B;
while(p)
{
while(p->next)
{
t = t->next;
p = p->next;
}
if(p->data != s->data)
{
s->next = p;
s = s->next;
}
else free(p);
t->next = NULL;
t = A;
p = A->next;
}
while(q)
{
while(q->next)
{
k = k->next;
q = q->next;
}
if(q->data > s->data)
{
s->next = q;
s = s->next;
}
else free(q);
k->next = NULL;
k = B;
q = B->next;
}
}
void Print(LNode link)
{
LNode p = link->next;
while(p)
{
printf("%4d",p->data);
p = p->next;
}
printf("\n");
}
int main()
{
LNode A = (LNode)malloc(sizeof(Node));
LNode B = (LNode)malloc(sizeof(Node));
LNode C = (LNode)malloc(sizeof(Node));
int lenA = 0, lenB = 0;
int x = 0, y = 0;
srand((unsigned)time(0));
A->next = NULL;
B->next = NULL;
C->next = NULL;
printf("A表长度:");
scanf("%d", &lenA);
printf("B表长度:");
scanf("%d", &lenB);
/*生成数据*/
while(lenA>0||lenB>0)
{
if(lenA>0)
{
x = rand()&255;
if(x>=0)
{
Add(A, x);
lenA--;
}
}
if(lenB>0)
{
x = rand()&255;
if(x>=0)
{
Add(B, x);
lenB--;
}
}
}
printf("A:");
Print(A);
printf("B:");
Print(B);
Merge(A,B,C);
printf("C:");
Print(C);
return 0;
}
[[it] 本帖最后由 hellbelial 于 2008-4-29 04:31 编辑 [/it]]