1025 反转链表
四个注意的点:
1.输入的节点有的可能是无效的
2.最后输出的时候因为有反转,所以节点的下一个地址也变了
3.输出最好用printf,用cout第五个测试用例会超时
4. printf输出string类型的时候,要加.c_str(),否则会出现乱码
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
struct LinkedList
{
string addres;
string next;
int val;
};
int main()
{
string first_add;
int n, k;
cin >> first_add >> n >> k;
vector<LinkedList> list(n);
map <string, LinkedList> Li;
for (int i = 0; i < n; i++)
{
cin >> list[i].addres >> list[i].val >> list[i].next;
Li.insert(pair<string, LinkedList>(list[i].addres, list[i]));
}
vector<LinkedList> result;
//建立正确顺序的链表
while (true)
{
if (first_add!="-1")
{
result.push_back(Li[first_add]);
first_add = Li[first_add].next;
}
else
{
break;
}
}
//输入的节点有的是无效的
//节点的地址也变了
//输出最好用printf,用cout第五个测试用例会超时
n = result.size();
for (int i = 0; i <n; i+=k)
{
if (i+k<=n)
{
reverse(result.begin() + i, result.begin() + i + k);
}
}
for (int i = 0; i < n-1; i++)
{
printf("%s %d %s\n", result[i].addres.c_str(), result[i].val, result[i+1].addres.c_str());
}
printf("%s %d -1\n", result[n-1].addres.c_str(), result[n-1].val);
return 0;
}