题目
给定一个常数 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 (≤105)、以及正整数 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
分析
这是一道链表反转的题,记住链表的题不一定就要用数组模拟链表来做,这道题非常经典,很重要其中的一些操作方法,电脑上有debug注释
AC代码
#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;
const int N = 1e5 + 10;
int head, n, k;
typedef struct{
int address; int zhi; int nextaddress;
}LINK;
LINK a[N], l;
vector<LINK> sort_a, reverse_a;
void sort_LINK ()
{
int ne = head;
while(ne != -1)
{
sort_a.push_back(a[ne]);
ne = a[ne].nextaddress; //***
}
}
void reverse_LINK ()
{
int temp = k - 1;
while(temp < sort_a.size()) //不能等于
{
for(int i = temp ; i > temp - k ; i -- )
{
reverse_a.push_back(sort_a[i]);
}
temp += k;
}
for(int i = temp - k + 1 ; i < sort_a.size() ; i ++ ) reverse_a.push_back(sort_a[i]);
}
int main ()
{
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin>>head>>n>>k;
for(int i = 0 ; i < n ; i ++ )
{
cin>>l.address>>l.zhi>>l.nextaddress; //***
a[l.address] = l; //***
}
sort_LINK();
reverse_LINK();
//修改nextaddres
for(int i = 0 ; i < reverse_a.size() - 1 ; i ++ )
{
reverse_a[i].nextaddress = reverse_a[i + 1].address; //如果最后一个reverse了那么这里的修改没有修改到reverse之后的最后一个的next指针
}
for(int i = 0 ; i < reverse_a.size() ; i ++ )
{
cout<<setw(5)<<setfill('0')<<reverse_a[i].address<<" "<<reverse_a[i].zhi<<" ";
if(i == reverse_a.size() - 1) cout<<-1<<endl;
else cout<<setw(5)<<setfill('0')<<reverse_a[i].nextaddress<<"\n";
}
return 0;
}