首页 > 其他 > 详细

链表的简单实现

时间:2014-05-13 10:46:59      阅读:400      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
 1 #include <cstdio>
 2 #include <cassert>
 3 
 4 typedef struct node {
 5     int data;
 6     node * next;
 7 }Node, *pNode;
 8 
 9 pNode CreateList() {
10     pNode head, p1, p2;
11     p1 = new Node;
12     printf("Please input data: \n");
13     scanf("%d", &p1->data);
14     int n = 0;
15 
16     while (p1->data != 0) {
17         n++;
18         if (n == 1)
19             head = p1;
20         else
21             p2->next = p1;
22         p2 = p1;
23         p1 = new Node;
24         scanf("%d", &p1->data);
25     }
26     p2->next = NULL;
27     return head;
28 }
29 
30 void Sort(pNode head) {
31     for (pNode p = head; p != NULL; p = p->next) {
32         for (pNode q = p->next; q != NULL; q = q->next) {
33             if (q->data < p->data) {
34                 int tmp = p->data;
35                 p->data = q->data;
36                 q->data = tmp;
37             }
38         }
39     }
40 }
41 
42 pNode Merge(pNode head1, pNode head2) {
43     assert(head1 != NULL && head2 != NULL);
44 
45     Sort(head1);
46     Sort(head2);
47 
48     pNode head, end;
49     bool first = true;
50 
51     while (true) {
52         if (head1 == NULL) {
53             end->next = head2;
54             break;
55         }
56         else if (head2 == NULL) {
57             end->next = head1;
58             break;
59         }
60         if (head1->data >= head2->data) {
61             pNode p = new Node;
62             p->data = head2->data;
63             head2 = head2->next;
64             if (first) {
65                 first = false;
66                 head = p;
67             }
68             else
69                 end->next = p;
70             end = p;
71         }
72         else {
73             pNode p = new Node;
74             p->data = head1->data;
75             head1 = head1->next;
76             if (first) {
77                 first = false;
78                 head = p;
79             }
80             else
81                 end->next = p;
82             end = p;
83         }
84     }
85     return head;
86 }
87 
88 int main()
89 {
90     pNode plist1 = CreateList();
91     pNode plist2 = CreateList();
92 
93     pNode plist3 = Merge(plist1, plist2);
94     for (pNode p = plist3; p != NULL; p = p->next)
95         printf("%d\n", p->data);
96 
97     return 0;
98 }
bubuko.com,布布扣

 

链表的简单实现,布布扣,bubuko.com

链表的简单实现

原文:http://www.cnblogs.com/aoun/p/3724593.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!