背景:由于书上讲的链表的归并多是采用有序数列,这里的程序采用无序链表,基本思想是:链表2的每一个元素与链表1中的元素比较,如果链表2的其中一个元素是链表1中没有的,那么就把此元素插在链表1的末尾。(思想非常自然)
以下是c语言源代码:
//author:Chris_zhong
//1.0版本
//在VC6下面编译通过,只能输入数字,链表以数字零结尾,在后面的版本会得到改进。
#include
#include
#define LEN sizeof(struct node)
struct node
{
int num;
struct node *next;
};
int n;
struct node *creat(void);
void linklist_show(struct node *);
struct node *copy(struct node *);
int check_num(struct node *,int);
struct node *insert_tail(struct node *, int);
//int check_two_list(struct node *,struct node *);
struct node * two_linklist_merge(struct node *head1,struct node
*head2);
void main()
{ struct node *La,*Lb,*Lc;
La=creat();
Lb=creat();
printf("is merging\n");
Lc = two_linklist_merge(La,Lb);
linklist_show(Lc);
}
//创建链表,(需要改进使得不必以数字0结尾)
struct node *creat(void)
{
struct node *head;
struct node *p1,*p2;
n=0;
p1=p2=(struct node *)malloc(LEN);
scanf("%d",&p1->num);
// head=NULL;
while(p1->num!=0)
{
n=n+1;
if(n==1) head=p1;
else
p2->next=p1;//
让P1指向新开辟的节点,p2指向链表中最后一个节点,吧p1所指的节点连接在p2所指的节点后面。
p2=p1;
p1=(struct node
*)malloc(LEN);//又开始开辟新的内存空间
scanf("%d,%d",&p1->num);//输入节点元素值
}
p2->next=NULL;//已经到了链表尾部
return(head);
}
//显示链表元素函数
void linklist_show(struct node *head)//void
{
struct node *p;
p=head;
do {
printf("%d\n",p->num);
p=p->next;
}while(p!=NULL);
}
//末尾插入元素函数
struct node *insert_tail(struct node *head, int number)
{
struct node *p1,*p;
p=head;
while((p->next) != NULL)
p =
p->next;//当p不是末尾元素的时候,移动指针,当p是末尾的时候,开辟新的节点p1,使得p-》next为p1,p1的数据为number,next为NULL
p1 = (struct node *)malloc(LEN);
p->next = p1;
(p1->num) = number;
(p1->next) = NULL;
return (head);
}
//检测输入值number是否等于链表中的值,如果等于返回真,否则,返回假
int check_num(struct node *head,int number)
{
struct node *p;int a;
p = head;
while(p!=NULL)
{
if( number==
(p->num))
{a=1;break;}
else
{a=0;}//这里不要有break。意思相当于如果没有遇到相同的数字,则一直检测下去,知道a等于1为止。否则a等于0
p =
p->next;
}
return a;
}
struct node *two_linklist_merge(struct node *head1,struct node
*head2)//head1源链表,head2目标链表,两个链表归并
{
struct node *p1,*p2;
p1 = head1;
p2 = head2;
while(p2!=NULL)
{
if(!(check_num(p1,p2->num)))//如果不是链表1中的值,则吧p2->num插入p1链表
insert_tail(p1,p2->num);
p2 =
p2->next;
}
return head1;
}
总结:此功能只是最基本的功能,目标是复习数据结构和指针,结构体方面的知识,特别是链表创建函数,值得改进的地方还有很多,感觉自己编程比看别人的源代码舒服点。