归并链表

 1 #include<iostream.h>
2 #include<malloc.h>
3 struct node
4 {
5 int data;
6 struct node *next;
7 };
8 void traverse_list(struct node *head)
9 {
10 int i = 1;
11 struct node *p;
12 p = head->next;
13 while(p)
14 {
15 if(i != 1)
16 cout<<' ';
17 cout<<p->data;
18 p = p->next;
19 i++;
20 }
21 cout<<endl;
22 }
23 struct node *creat(int k)
24 {
25 struct node *head,*p,*tail;
26 head = (struct node *)malloc(sizeof(struct node));
27 head->next = NULL;
28 tail = head;
29 while(k--)
30 {
31 p = (struct node *)malloc(sizeof(struct node));
32 cin>>p->data;
33 p->next = NULL;
34 tail->next = p;
35 tail = p;
36 }
37 return head;
38 }
39 void merge(struct node *head1,struct node *head2)
40 {
41 struct node *p,*q,*tail;
42 p = head1->next;
43 q = head2->next;
44 tail = head1;
45 while(p&&q)
46 {
47 if(p->data<q->data)
48 {
49 tail->next = p;
50 tail = p ;
51 p = p->next;
52 }
53 else
54 {
55 tail->next = q;
56 tail = q;
57 q = q->next;
58 }
59 }
60 if(p)
61 tail->next = p;
62 else
63 tail->next = q;
64 traverse_list(head1);
65 }
66 int main()
67 {
68 int m, n;
69 struct node *head1,*head2;
70 cin>>m>>n;
71 head1 = creat(m);
72 head2 = creat(n);
73 merge(head1,head2);
74 return 0;
75 }

 

转载于:https://www.cnblogs.com/shangyu/archive/2012/02/10/2345691.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值