研究了一个星期的单链表合并算法c语言实现devC++正常编译运行
#define TRUE 1#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFELOW -2
#include<stdio.h>
#include<malloc.h>
typedef int Status;
typedef int ElemType;
typedef struct node
{
ElemType data;
struct node * next;
}node, *LinkList;
LinkList creat(void);
void Print(LinkList head);
void MergeList(LinkList head1,LinkList head2,LinkList head3);
int main(void)
{
LinkList La_head = NULL;
LinkList Lb_head = NULL;
LinkList Lc_head = (LinkList)malloc(sizeof(node));
La_head = creat();
Lb_head = creat();
Print(La_head);
Print(Lb_head);
MergeList(La_head,Lb_head,Lc_head);
Print(Lc_head);
system("pause");
}
LinkList creat(void)
{
int length;
int i;
int veriables;
LinkList head = (LinkList)malloc(sizeof(node));
if(NULL == head)
{
printf("No enough space!");
exit(-1);
}
LinkList tail = head;
printf("Input LinkList Length: ");
scanf("%d",&length);
printf("\n");
for(i=0;i<length;++i)
{
printf("Input number %d elem: ",i+1);
scanf("%d",&veriables);
LinkList pnew = (LinkList)malloc(sizeof(node));
if(NULL == pnew)
{
printf("No enough space!");
exit(-1);
}
pnew->data = veriables;
tail->next = pnew;
pnew->next = NULL;
tail = pnew;
}
printf("\n\n");
return (head);
}
void Print(LinkList head)
{
LinkList p = head->next;
while(p)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n\n");
}
void MergeList(LinkList head1,LinkList head2,LinkList head3)
{
LinkList La = head1->next;
LinkList Lb = head2->next;
LinkList Lc = head3;
LinkList q;
while(La && Lb)
{
if(La->data < Lb->data)
{
Lc->next = La;
Lc = La;
La = La->next;
}
else if(La->data == Lb->data)
{
Lc->next = La;
Lc = La;
La = La->next;
q = Lb;
Lb = Lb->next;
free(q);
}
else
{
Lc->next = Lb;
Lc = Lb;
Lb = Lb->next;
}
}
Lc->next = La ? La : Lb;
free(head1);
free(head2);
}
研究了一个星期希望对大家有帮助 无回帖,不论坛,这才是人道。
页:
[1]