1025 反转链表 测试点3和测试点6
易错点
测试点3:k=1的情况
测试点6:有无效结点,此时结点总个数不等于要反转的链表的结点总个数
代码
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int a[100001];
string nxt[100001];
string p[100001];
int main()
{
string faddr;
int n,k;
string address;
int data;
string nex;
string final;
string f;
string tmpf;
string fir;
string tmpf2;
int tmp=0;
int tmp2=0;
int len=1;
cin>>faddr>>n>>k;
for(int i=0;i<n;i++){
cin>>address>>data>>nex;
a[stoi(address)]=data;
nxt[stoi(address)]=nex;
if(nex=="-1"){
final=address;
}
}
f=faddr;
p[stoi(f)]="-1";
while(nxt[stoi(f)]!="-1"){
p[stoi(nxt[stoi(f)])]=f;
f=nxt[stoi(f)];
len++;
}
f=final;
if(k!=1){
if(len%k>=2){
for(int i=0;i<len%k-1;i++){
f=p[stoi(f)];
}
tmpf=f;
fir=p[stoi(f)];
}
else if(len%k==1){
tmpf=f;
fir=p[stoi(f)];
}
else if(len%k==0){
tmpf="-1";
tmp2=1;
}
while(p[stoi(f)]!="-1"){
if(tmp2==1){
fir=f;
tmp2=0;
nxt[stoi(f)]=p[stoi(f)];
for(int i=0;i<k-2;i++){
f=p[stoi(f)];
nxt[stoi(f)]=p[stoi(f)];
}
}
else{
fir=p[stoi(f)];
for(int i=0;i<k-1;i++){
f=p[stoi(f)];
nxt[stoi(f)]=p[stoi(f)];
}
}
f=p[stoi(f)];
nxt[stoi(f)]=tmpf;
tmpf=fir;
if(p[stoi(f)]!="-1"){
fir=p[stoi(f)];
}
}
}
else if(k==1){
fir=faddr;
}
f=fir;
while(nxt[stoi(f)]!="-1"){
cout<<f<<" "<<a[stoi(f)]<<" "<<nxt[stoi(f)]<<endl;
f=nxt[stoi(f)];
}
cout<<f<<" "<<a[stoi(f)]<<" "<<nxt[stoi(f)]<<endl;
return 0;
}

浙公网安备 33010602011771号