遍历链表,在遍历的时候比较,小的先插入新链表就可以了,你的hb代码看着没有问题,那么就是在创建链表的时候,根据随机生成的数插入链表中,使之非递减。
代码及运行结果如下:
代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct lnode
{
int data;
struct lnode* next;
}Lnode;
Lnode* inserNode(Lnode* head, Lnode* p)
{
Lnode* pre,*t;
pre = head;
t = pre->next;
while (t)
{
if (t->data >= p->data)
break;
else
{
pre = t;
t = t->next;
}
}
if (t == 0)
{
pre->next = p;
}
else
{
pre->next = p;
p->next = t;
}
return head;
}
Lnode* CreateList(int n)
{
int i;
Lnode* head = (Lnode*)malloc(sizeof(Lnode));
Lnode* t;
head->next = 0;
for (i = 0; i < n; i++)
{
t = (Lnode*)malloc(sizeof(Lnode));
t->data = rand()%100; //生成0~99的整数
t->next = 0;
head = inserNode(head, t);
}
return head;
}
Lnode* hb(Lnode* pa, Lnode* pb)
{
Lnode* p, * q, * pc;
pb = pb->next;
pa = pa->next;
pc = (Lnode*)malloc(sizeof(Lnode));
p = pc;
while (pa && pb)
{
q = (Lnode*)malloc(sizeof(Lnode));
if (pb->data < pa->data)
{
q->data = pb->data;
pb = pb->next;
}
else
{
q->data = pa->data;
pa = pa->next;
}
p->next = q;
p = q;
}
while (pa)
{
q = (Lnode*)malloc(sizeof(Lnode));
q->data = pa->data;
pa = pa->next;
p->next = q;
p = q;
}
while (pb)
{
q = (Lnode*)malloc(sizeof(Lnode));
q->data = pb->data;
pb = pb->next;
p->next = q;
p = q;
}
p->next = NULL;
return(pc);
}
//显示
void printList(Lnode* head)
{
Lnode* p;
if (head == 0 || head->next == 0)
{
printf("链表为空\n");
return;
}
else
{
p = head->next;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
}
int main()
{
int m, n;
Lnode* la=0, *lb=0,*lc=0;
srand((unsigned int)time(NULL));
printf("请数量链表A和链表B的长度:");
scanf("%d %d", &m, &n);
la = CreateList(m);
printf("链表A:");
printList(la);
lb = CreateList(n);
printf("链表B:");
printList(lb);
lc = hb(la, lb);
printf("合并后的链表为:");
printList(lc);
return 0;
}