浙大MOOC《数据结构》PTA第4题 Reversing Linked List
作者:互联网
题目链接
题目及样例
代码
#include <iostream>
#include <algorithm>
using namespace std;
#define maxsize 100002
struct LNode {
int Data;
int Next;
}a[maxsize];
int list[maxsize];//每个结点的地址
int Head,N,K,p;//第一个节点地址,所有结点数,翻转子序列长度
int main() {
cin >> Head >> N >> K;
list[0] = Head;
for(int i = 0; i < N; ++i) {
int index, data, next;
cin >> index >> data >> next;
a[index].Data = data;
a[index].Next = next;
}
p = a[Head].Next;
int sum = 1;
while(p != -1) {
list[sum++] = p;
p = a[p].Next;
}
int j = 0;
while(j + K <= sum) {
reverse(&list[j], &list[j+K]);
j = j + K;
}
for(int i = 0; i < sum-1; ++i) {
int id = list[i];//第i个结点的索引
printf("%05d %d %05d\n", id, a[id].Data, list[i+1]);
}
printf("%05d %d -1\n", list[sum-1], a[list[sum-1]].Data);
return 0;
}
标签:index,Reversing,Head,int,List,sum,list,MOOC,Next 来源: https://blog.csdn.net/qq_51691526/article/details/120217335