wenbao与链表

 

两个非递减的链表合并为一个严格递减链表

 

 

 

 1 #include <iostream>
 2 #include <stdio.h>
 3 using namespace std;
 4 struct Node{
 5     int x;
 6     Node* next;
 7 };
 8 Node *add(int xx, Node *q){
 9     Node *pp;
10     pp = new Node;
11     pp -> x = xx, pp -> next = q;
12     return pp;
13 }
14 Node *creat(Node *p, int n){
15     Node *pp, *q;
16     pp = p = NULL;
17     for(int i = 0; i < n; ++i){
18         q = new Node;
19         scanf("%d", &q->x);
20         q->next = NULL;
21         if(pp == NULL) p = q;
22         else pp->next = q;
23         pp = q;
24     }
25     return p;
26 }
27 void uni(Node *p, Node *p2){
28     Node *p3, *pp;
29     p3 = NULL;
30     while(p != NULL || p2 != NULL){
31         if(p == NULL){
32             if(p2->x > p3->x)    p3 = add(p2->x, p3);
33             p2 = p2->next;
34         }else if(p2 == NULL){
35             if(p->x > p3->x)    p3 = add(p->x, p3);
36             p = p->next;
37         }else{
38             if(p->x == p2->x){
39                 if(p3 == NULL || p->x != p3->x)    p3 = add(p->x, p3);
40                 p = p->next, p2 = p2->next;
41             }else if(p->x > p2->x){
42                 if(p3 == NULL || p3->x != p2->x)    p3 = add(p2->x, p3);
43                 p2 = p2->next;
44             }else{
45                 if(p3 == NULL || p3->x != p->x)    p3 = add(p->x, p3);
46                 p = p->next;
47             }
48         }
49     }
50     for(pp = p3; pp != NULL; pp = pp->next)    printf("%d\n", pp->x);
51 }
52 int main(){
53     Node *p, *p2;
54     int n, m;
55     scanf("%d", &n);
56     p = creat(p, n);
57     scanf("%d", &m);
58     p2 = creat(p2, m);
59     uni(p, p2);
60     return 0;
61 }

 

 

 

 

 

只有不断学习才能进步!

 

posted @ 2018-04-14 13:52  wenbao  阅读(96)  评论(0编辑  收藏  举报