給定一個單鏈表 L1 →L2 →⋯→Ln−1 →Ln ,請編寫程序將鏈表重新排列爲 Ln →L1 →Ln−1 →L2 →⋯。例如:給定L爲1→2→3→4→5→6,則輸出應該爲6→1→5→2→4→3。
輸入格式:
每個輸入包含1個測試用例。每個測試用例第1行給出第1個結點的地址和結點總個數,即正整數N (≤10^5 )。結點的地址是5位非負整數,NULL地址用−1表示。
接下來有N行,每行格式爲:
Address Data Next
其中Address
是結點地址;Data
是該結點保存的數據,爲不超過10^5 的正整數;Next
是下一結點的地址。題目保證給出的鏈表上至少有兩個結點。
輸出格式:
對每個測試用例,順序輸出重排後的結果鏈表,其上每個結點佔一行,格式與輸入相同。
輸入樣例:
00100 6
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218
輸出樣例:
68237 6 00100
00100 1 99999
99999 5 12309
12309 2 00000
00000 4 33218
33218 3 -1
#include <iostream>
#include <vector>
#include <map>
#include <queue>
using namespace std;
struct Node {
int address,
data,
next;
};
int main() {
map<int, Node>link;
deque<Node>q;
vector<Node>v;
int head, N, tmp;
cin >> head >> N;
for (int i = 0; i < N; ++i) {
cin >> tmp;
cin >> link[tmp].data >> link[tmp].next;
}
while (head != -1) {
q.push_back({ head,link[head].data,0 });
head = link[head].next;
}
while (!q.empty()) {
v.push_back(q.back()), q.pop_back();
if (!q.empty())
v.push_back(q.front()), q.pop_front();
}
for (int i = 0; i < v.size(); ++i)
printf("%05d %d ", v[i].address, v[i].data),
i + 1 == v.size() ? printf("-1\n") : printf("%05d\n", v[i + 1].address);
return 0;
}