L2-2 重排鏈表 (25 分)
給定一個單鏈表 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 (≤105)。結點的地址是5位非負整數,NULL地址用−1表示。
接下來有N行,每行格式爲:
Address Data Next
其中Address
是結點地址;Data
是該結點保存的數據,爲不超過105的正整數;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 <algorithm> #include <string.h> #include <string> #include <math.h> #include <list> using namespace std; const int MAX = 100005; struct node{ int key; int next; }; node a[MAX]; int b[MAX],c[MAX]; int main(){ int n,m; cin>>n>>m; int address; for(int i=0;i<m;i++){ cin>>address; cin>>a[address].key; cin>>a[address].next; } int cnt = 0; int k1 = 0,k2 = 0; for(int i=n;i!=-1;i=a[i].next){ cnt++; if(cnt <= m / 2){ b[k1++] = i; } else{ c[k2++] = i; } } if(k1 == k2){ printf("%05d %d ",c[k2-1],a[c[k2-1]].key); for(int i=0;i<k1;){ printf("%05d\n",b[i]); printf("%05d %d ",b[i],a[b[i]].key); i++; if(i>=k1){ break; } printf("%05d\n",c[k2-1-i]); printf("%05d %d ",c[k2-1-i],a[c[k2-1-i]].key); } printf("-1"); } else{ int i=0; while(k1 || k2){ if(k2){ k2--; printf("%05d %d ",c[k2],a[c[k2]].key); if(k2>0) printf("%05d\n",b[i]); else{ printf("-1"); break; } } if(i<k1){ printf("%05d %d ",b[i],a[b[i]].key); printf("%05d\n",c[k2-1]); i++; } } } return 0; }
有個測試點一直wa!