给定一个常数 K 以及一个单链表 L,请编写程序将 L 中每 K 个结点反转。例如:给定 L 为 1→2→3→4→5→6,K 为 3,则输出应该为 3→2→1→6→5→4;如果 K 为 4,则输出应该为 4→3→2→1→5→6,即最后不到 K 个元素不反转。
【输入格式】:
每个输入包含 1 个测试用例。每个测试用例第 1 行给出第 1 个结点的地址、结点总个数正整数 N(≤10^5)、以及正整数 K (≤N),即要求反转的子链结点的个数。结点的地址是 5 位非负整数,NULL 地址用 −1 表示。
接下来有 N 行,每行格式为:
Address Data Next
其中 Address 是结点地址,Data 是该结点保存的整数数据,Next 是下一结点的地址。
【输出格式】:
对每个测试用例,顺序输出反转后的链表,其上每个结点占一行,格式与输入相同。
【输入样例】:
00100 6 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218
【输出样例】:
00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 6 -1
【注意点】:
1. 结构体记录
2. 翻转
3. 输出,注意格式
【AC代码】:
#pragma warning(disable:4996)
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
struct node
{
int address;
int data;
int next;
};
node a[100005], *b[100005];
int main()
{
int n, k, head, address, data, next;
scanf("%d%d%d", &head, &n, &k);
for (int i = 0; i < n; i++)
{
scanf("%d%d%d", &address, &data, &next);
a[address].address = address;
a[address].data = data;
a[address].next = next;
}
int i, j = 0;
for (i = head; i != -1; i = a[i].next)
{
b[j++] = &a[i];
}
for (i = 0; i <= j - k; i += k)
{
reverse(b + i, b + i + k);
}
for (i = 0; i < j; i++)
{
if (i != j - 1)
{
printf("%05d %d %05d\n", b[i]->address, b[i]->data, b[i + 1]->address);
}
else
{
printf("%05d %d -1", b[i]->address, b[i]->data);
}
}
return 0;
}
但是还有一点疑问,为什么在最后一个循环里面j不能换成i???
C++标准库---逆转元素reverse()&reverse_copy()
reverse(beg,end)
reverse_copy(sourceBeg,sourceEnd,destBeg)
reverse()会将区间[beg,end)内的元素全部逆序;
reverse_copy()会将源区间[sourceBeg,sourceEnd)内的元素复制到"以destBeg起始的目标区间",并在复制过程中颠倒安置次序;
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[10];
int b[10];
int i;
for (i = 0; i < 10; i++)
a[i] = i + 1;
for (i = 0; i < 10; i++)
cout << a[i] << "\t";
cout << endl << endl;
reverse(a, a + 4);
for (i = 0; i < 10; i++)
cout << a[i] << "\t";
cout << endl << endl;
reverse_copy(a, a + 4, b);
for (i = 0; i < 10; i++)
cout << b[i] << "\t";
cout << endl;
return 0;
}

333



被折叠的 条评论
为什么被折叠?



