您的位置:首页 > 理论基础 > 数据结构算法

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

2013-04-11 13:01 363 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐