c语言链表二路归并,两个无序链表归并的c语言程序1.0

背景:由于书上讲的链表的归并多是采用有序数列,这里的程序采用无序链表,基本思想是:链表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;

}

总结:此功能只是最基本的功能,目标是复习数据结构和指针,结构体方面的知识,特别是链表创建函数,值得改进的地方还有很多,感觉自己编程比看别人的源代码舒服点。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值