#include <iostream>
#include <iomanip>
#include <unordered_map>
#include <string>
using namespace std;
const int N = 100010;
unordered_map<string, string> neStr;
unordered_map<string, int> eStr;
string headStr;
int n;
// 反转链表函数(字符串版本)
string reverse(string headStr) {
string curStr = headStr, prevStr = "-1";
while (curStr != "-1") {
string tempStr = neStr[curStr];
neStr[curStr] = prevStr;
prevStr = curStr;
curStr = tempStr;
}
return prevStr;
}
// 获取链表的中间节点
string getMidNode(string headStr) {
if (neStr[headStr] == "-1") return headStr;
string fast = headStr;
string slow = headStr;
while (neStr[fast] != "-1" && neStr[neStr[fast]] != "-1") {
fast = neStr[neStr[fast]];
slow = neStr[slow];
}
return slow;
}
void print(string l)
{
string cur = l;
while (cur != "-1")
{
cout << eStr[cur] << ' ';
cur = neStr[cur];
}
}
// 合并两个链表
void merge(string l1, string l2) {
while (l1 != "-1" && l2 != "-1")
{
string n1 = neStr[l1], n2 = neStr[l2];
neStr[l2] = l1;
neStr[l1] = n2;
l2 = n2;
l1 = n1;
}
}
int main() {
cin >> headStr;
cin >> n;
for (int i = 1; i <= n; i++) {
string addrStr, nextStr;
int data;
cin >> addrStr >> data >> nextStr;
eStr[addrStr] = data;
neStr[addrStr] = nextStr;
}
// 处理链表
string mid = getMidNode(headStr);
string nextPart = reverse(neStr[mid]);
neStr[mid] = "-1"; // 断开链表的前半部分和后半部分
/*cout << endl;
print(headStr);
cout << endl;
print(nextPart);*/
merge(headStr, nextPart);
cout << endl;
// 打印链表
string cur = nextPart;
while (cur != "-1") {
cout << setw(5) << setfill('0') << cur << ' ' << eStr[cur] << ' ' << neStr[cur] << endl;
cur = neStr[cur];
}
return 0;
}
标签:headStr,string,pta,链表,curStr,fast,重排,neStr
From: https://www.cnblogs.com/windzhao6/p/18417016