解题代码
#include<stdio.h>
#include<stdlib.h>
typedef struct Array array;
struct Array {
int expon;
int next;
};
int main()
{
array a[100000];
int i, j, head, N, reN, taddress, texpon, tnext, cnt, realN=0;
scanf("%d %d %d", &head, &N, &reN);
for (i = 0; i < N; i++) {
scanf("%d %d %d", &taddress, &texpon, &tnext);
a[taddress].expon = texpon;
a[taddress].next = tnext;
}
int p = head;
while (p!=-1) {
realN++;
p = a[p].next;
}
cnt = realN / reN;
int t, r, s, temp, flag=1;
p = head, t = head, r = head, s = a[head].next;
for (i = 0 ; i < cnt; i++) {
for (j = 0; j < reN - 1;j++) {
temp = a[s].next;
a[s].next = r;
r = s;
s = temp;
}
if (flag) {
head = r;
flag = 0;
}
if (i == cnt - 1 && s != -1) {
a[p].next = r;
a[t].next = s;
}
else if (i == cnt - 1) {
a[p].next = r;
a[t].next = -1;
}else if (i > 0 && i < cnt) {
a[p].next = r;
p = t;
}
t = s;
r = s;
s = a[s].next;
}
p = head;
flag = 1;
while (a[p].next!=-1) {
if (flag) flag = 0;
else printf("\n");
printf("%05d %d %05d",p,a[p].expon,a[p].next);
p = a[p].next;
}
if (flag) flag = 0;
else printf("\n");
printf("%05d %d %d", p, a[p].expon, a[p].next);
return 0;
}
测试结果
问题整理
1.这题他大爷的。。。
2. if (i == cnt - 1 && s != -1) {
a[p].next = r;
a[t].next = s;
}
else if (i == cnt - 1) {
a[p].next = r;
a[t].next = -1;
}else if (i > 0 && i < cnt) {
a[p].next = r;
p = t;
}//注意这段代码的判断逻辑。
3.注意会有多余结点不在链表上。