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

前端之家收集整理的这篇文章主要介绍了【数据结构】单链表(无头节点)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
#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.f2er.com/datastructure/383207.html

猜你在找的数据结构相关文章