题解
题干
输入格式
输出格式
输入样例
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
预备知识
函数原型:
reverse(iterator beg, iterator end);
功能:反转指定范围的元素
beg 起始迭代器
end 结束迭代器 (指向容器最后一个元素的下一个位置)
想法
可以使用两个数组来创建模拟链表,再遍历整个链表。用一个数组存储地址,通过reverse函数将指定区间的地址反转从而达到反转链表的效果。
注意:输入的数据可能包含脱离链表的结点,因此在遍历链表的同时需统计节点的总数。
代码
1.借助库函数,此思路不是原创,但相比自己手动反转效率要高(巨佬除外)。
#include<bits/stdc++.h>
using namespace std;
int main()
{
int data[100005],next[100005],list[100005];
int head, n,k;
cin>>head>>n>>k;
for(int i=0;i<n;i++)
{
int temp;
cin>>temp;
cin>>data[temp]>>next[temp];
}
int first=head,num=0;
while(first!=-1)
{
list[num++]=first;
first=next[first];
}
int sum=num;
num=num/k;
// cout<<"num"<<num<<endl;;
for(int i=0;num>0;i+=k)
{
num--;
reverse(begin(list)+i,begin(list)+i+k);//核心代码
}
for(int i=0;i<sum-1;i++)
{
printf("%05d %d %05d\n",list[i],data[list[i]],list[i+1]);
}
printf("%05d %d -1",list[sum-1],data[list[sum-1]]);//需要单独处理最后的-1
return 0;
}
2.手动反转,复杂,有些绕,并且其中一个测试点超时了,其它的测试点全部通过。。。
#include<bits/stdc++.h>
using namespace std;
class node
{
public:
void get_node(string m_loc,int m_data,string m_next){
loc=m_loc;
data=m_data;
next=m_next;
}
string loc;
int data;
string next;
};
string listrev(vector<node> &nodes,map<string,node> &mapp,string &head,int m,int n);
int main()
{
map<string ,node>mapp;
int n,k;
vector<node>nodes;
string head;
cin>>head>>n>>k;
for(int i=0;i<n;i++)
{
string temp1,temp2;
int tem;
cin>>temp1>>tem>>temp2;
node temp;
temp.get_node(temp1,tem,temp2);
nodes.push_back(temp);
mapp[temp1]=temp;
}
n=0;
{
string i=head;
while(i!="-1")
{
i=mapp[i].next;
n++;
}
}
int num=n/k;
if(num==0)
{
string i=head;
while(i!="-1")
{
cout<<mapp[i].loc<<mapp[i].data<<" "<<mapp[i].next<<endl;
i=mapp[i].next;
}
}
else
{
int i=1,j=k;
do
{
head=listrev(nodes,mapp,head,i,j);
i+=k;
j+=k;
} while (--num);
}
{
string i=head;
while(i!="-1")
{
cout<<mapp[i].loc<<" "<<mapp[i].data<<" "<<mapp[i].next<<endl;;
nodes.push_back(mapp[i]);
i=mapp[i].next;
}
}
return 0;
}
string listrev(vector<node> &nodes,map<string,node> &mapp,string &head,int m,int n)
{
//<可能出现的一些特殊情况:m = 1表示为头结点,n = length为尾节点,m = n不进行翻转,这三种情况都要考虑到
//<这里采用的方法就是将不进行翻转的部分的节点先保存下来,需要翻转的先翻转,然后再连接上
if (head == "-1")
return "-1";
string begin = "-1"; //<因为是记录m节点的前一个节点,所以一开始应该赋值为NULL
string cur = head;
for(int i = 0; i < m - 1; i++)
{
begin = cur;
cur = mapp[cur].next;
}
string end = cur; //<翻转过后这个点就是最后一个节点了
string pPre = cur; // pre cur pNext 三个之间进行交换
cur = mapp[cur].next;
for(int i = m + 1; i <= n; i++) //<n这里直接走到了n已经是翻转链表的下一个位置了
{
string pNext = mapp[cur].next;
mapp[cur].next = pPre;
pPre = cur;
cur = pNext; //<通过cur得到下一个节点,画图明显
}
mapp[end].next = cur;
if (begin!="-1")
mapp[begin].next = pPre;
else head = pPre;
return head;
}