1.待合并的两个链表分别为A,B。
2.用a,b分别指向a,b,以便比较数据域大小。
3.用指针p指向待插入合成链表的节点(红色所指)。
4.红色连线即头插法的顺序 。
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node,*list;
list create(){
list L;
int c;
L = (list)malloc(sizeof(node));
L->next = NULL;
node *p , *tail;
tail = L;
c = getchar();
while(c != '#'){
p = (node *)malloc(sizeof(node));
p->data = c;
tail->next = p;
tail = p;
c = getchar();
}
tail->next = NULL;
return L;
}
void Showlist(list A)
{
node *p = A->next;
while(p != NULL)
{
printf("%c",p->data );
p = p->next ;
}
return ;
}
list Mergelist(list A,list B)
{
node *a,*b,*p;//p用来指向下一个被操作的结点
list newlist;//新建一个头结点
newlist = A;//用A的头结点,不浪费
newlist = (node*)malloc(sizeof(node));
p = NULL;
a = A->next ;
b = B->next ;
while(a&&b)
{
if(a->data <= b->data )
{
p = a;
a = a->next ;
p->next = newlist->next ;//头插法,实现倒序
newlist->next = p;
}
else
{
p = b;
b = b->next ;
p->next = newlist->next ;
newlist->next = p;
}
}
if(a)a=b;//其中一个已遍历完
while(a)
{
p = a;
a = a->next ;
a->next = newlist->next ;
newlist->next = a;
}
return newlist;
}
int main()
{
list A,B,newlist;
A = (list)malloc(sizeof(node));
B = (list)malloc(sizeof(node));
A = create();
printf("展示链表A:");
Showlist(A);
B = create();
printf("展示链表B:");
Showlist(B);
newlist = Mergelist(A,B);
printf("展示合并后的链表:");
Showlist(newlist);
return 0;
}