給定一個單鏈表 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 (≤)。結點的地址是5位非負整數,NULL地址用−表示。
接下來有N行,每行格式為:
Address Data Next
其中Address
是結點地址;Data
是該結點保存的數據,為不超過1的正整數;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 <cstdio> #include <cstdlib> #include <algorithm> #include <set> using namespace std; struct link { int Next,Data; }l[1000000]; int num[1000000]; int main() { int n,data,add,nadd,sadd; cin>>sadd>>n; for(int i = 0;i < n;i ++) { cin>>add>>data>>nadd; l[add].Data = data; l[add].Next = nadd; } int c = 0,t = sadd; while(t != -1) { num[c ++] = t; t = l[t].Next; } for(int i = 1;i <= c;i ++) { if(i % 2) t = c - (i + 1) / 2; else t = (i - 1) / 2; if(i > 1) printf(" %05d\n",num[t]); printf("%05d %d",num[t],l[num[t]].Data); } cout<<' '<<-1; }