BJFU-225- merge two increments based on an ordered sequence of linked list

  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 typedef struct Lnode{
  4     int num;
  5     struct Lnode * next;
  6 }Lnode,*LinkList;
  7 
  8 typedef struct Link{
  9     LinkList data;
 10     struct Link * next;
 11 }Link,*List;
 12 void creatList(LinkList &L,int n)
 13 {
 14     L = (LinkList)malloc(sizeof(Lnode));
 15     L->next = NULL;
 16     LinkList rear = L;
 17 
 18     for(int i=1;i<=n;i++)
 19     {
 20         LinkList p = (LinkList)malloc(sizeof(Lnode));
 21 
 22         scanf("%d",&p->num);
 23         rear->next = p;
 24         p->next = NULL;
 25         rear = p;
 26     }
27  }
 28  void Traverse (LinkList L)
 29  {
 30      LinkList L-P => Next;
 31 is      the while (P)
 32      {
 33 is          IF (p-> Next == NULL)
 34 is          {
 35              the printf ( " % D " , p- > NUM); // output of the last digit can not have spaces, otherwise the compiler pass. Do not ask me why! ! !
36          } the else {
 37 [              the printf ( " % D " , p-> NUM);
 38 is          }
 39  
40          P = p->next;
 41     }
 42     printf("\n");
 43 }
 44 LinkList mergeList(LinkList La,LinkList Lb,int n,int m)
 45 {
 46     LinkList Lc,a,b,c;
 47     Lc = La;
 48     a = La->next;
 49     b = Lb->next;
 50     c = Lc;
 51 
 52     while(a&&b)
 53     {
 54         if(a->num > b->num)
 55         {
 56             c->next = b;
 57             c = b;
 58             b = b->next;
 59         }else if(a->num==b->num)
 60         {
 61             LinkList q = b;
 62             c->next = a;
 63             c = a;
 64             a = a->next;
 65             b = b->next;
 66             free(q);
 67         }else
 68         {
 69             c->next = a;
 70             c = a;
 71             a = a->next;
 72         }
 73     }
 74 
 75     c->next = a?a:b;
 76     free(Lb);
 77     return Lc;
 78 }
 79 int main()
 80 {
 81     int n,m;
 82 
 83     List Lc = (List)malloc(sizeof(Link));
 84     List r = Lc;
 85     while(1)
 86     {
 87         scanf("%d%d",&n,&m);
 88         if(n==0&&m==0) break;
 89         LinkList La,Lb;
 90         creatList(La,n);
 91         creatList(Lb,m);
 92 
 93         List pc = (List)malloc(sizeof(Link));
 94         LinkList Lc = mergeList(La,Lb,n,m);
 95         pc->data = Lc;
 96         r->next = pc;
 97         r = pc;
 98         pc->next = NULL;
 99 
100     }
101     List p = Lc->next;
102     while(p)
103     {
104         traverse(p->data);
105         p = p->next;
106     }
107 }

 

Guess you like

Origin www.cnblogs.com/wwww2/p/11745429.html