微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

【数据结构】单链表无头节点

#include "stdlib.h"
#include "stdio.h"
struct List {
    int xs;
    int zs;
    List *next;
};
void InstList(List *&L,int n) {
    L = (List *)malloc(sizeof(List));
    scanf("%d%d",&L->xs,&L->zs);
    L->next = NULL;
    List *p = L;
    for(int i = 0; i < n - 1; i++) {
        p->next = (List *)malloc(sizeof(List));
        p = p->next;
        scanf("%d%d",&p->xs,&p->zs);
        p->next = NULL;
    }
}
List *ListAdd(List *a,List *b) {
    List *c,*t,*Lc;
    if(a->zs > b->zs) {
        Lc = b;
    } else {
        Lc = a;
    }
    while(a && b) {
        if(a->zs > b->zs) {
            c->next = b;
            c = c->next;
            b = b->next;
        } else if(a->zs < b->zs) {
            c->next = a;
            c = c->next;
            a = a->next;
        } else if(a->zs == b->zs) {
            a->xs += b->xs;
            if(0 == a->xs) {
                t = a;
                a = a->next;
                t = b;
                b = b->next;
                free(t);
                free(t);
            } else {
                c->next = a;
                a = a->next;
                b = b->next;
                c = c->next;
            }
        }
    }
    if(!a)c->next = b;
    else if(!b)c->next = a;
    return Lc;
}
int main(void) {
    List *La,*Lb,*Lc;
    int lenla,lenlb;
    scanf("%d",&lenla);
    if(lenla < 1001) {
        InstList(La,lenla);
        scanf("%d",&lenlb);
        if(lenlb < 1001) {
            InstList(Lb,lenlb);
            Lc = ListAdd(La,Lb);
            while(Lc) {
                printf("%d %d\n",Lc->xs,Lc->zs);
                Lc = Lc->next;
            }
        }
    }
    return 0;
}

原文地址:https://www.jb51.cc/datastructure/383207.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐