数据结构——两个有序数组的合并

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 typedef int ElementType;
 5 typedef struct Node {
 6     ElementType data;
 7     struct Node  *next;
 8 }Lnode,*Linklist;
 9 
10 
11 void Read(Linklist *L)
12 {
13     int i,k,n;
14     Linklist s,rear;
15     *L = (Linklist)malloc(sizeof(Lnode));
16     rear = *L;
17     scanf("%d",&n);
18     for(i=0;i<n;i++)
19     {
20         s = (Linklist)malloc(sizeof(Lnode));
21         scanf("%d",&k);
22         s->data = k;
23         rear->next = s;
24         rear = s;
25     }
26     rear->next = NULL;
27 }
28 void Print( Linklist L )
29 {
30     Linklist p = L->next;
31     if(p==NULL)
32         printf("NULL\n");
33     else
34     {
35         while(p)
36     {
37         printf("%d ",p->data);
38         p = p->next;
39     }
40     printf("\n");
41     }
42 
43 
44 }
45 void Merge( Linklist *L1, Linklist *L2,Linklist *L )
46 {
47     Linklist pa = (*L1)->next;
48     Linklist pb = (*L2)->next;
49     Linklist pc = (Linklist)malloc(sizeof(Lnode));
50     *L = pc = *L1;
51     while(pa && pb)
52     {
53         if(pa->data <= pb->data)
54         {
55             pc->next = pa;
56             pc = pa;
57             pa = pa->next;
58         }
59         else
60         {
61             pc->next = pb;
62             pc = pb;
63             pb = pb->next;
64         }
65     }
66     pc->next = pa ? pa : pb;
67     free(*L2);
68 }
69 
70 
71 int main()
72 {
73     Linklist L1, L2, L;
74     Read(&L1);
75     Read(&L2);
76 
77     Merge(&L1, &L2, &L);
78     
79     Print(L);
80     return 0;
81 }
View Code

 

posted @ 2016-11-14 20:58  biu~biu~biu~  阅读(571)  评论(0编辑  收藏  举报