1. 程式人生 > >PAT Basic 1075

PAT Basic 1075

表示 i++ can ace mem 應該 memset data 相同

1075 鏈表元素分類

給定一個單鏈表,請編寫程序將鏈表元素進行分類排列,使得所有負值元素都排在非負值元素的前面,而 [0, K] 區間內的元素都排在大於 K 的元素前面。但每一類內部元素的順序是不能改變的。例如:給定鏈表為 18→7→-4→0→5→-6→10→11→-2,K 為 10,則輸出應該為 -4→-6→-2→7→0→5→10→18→11。

輸入格式:

每個輸入包含一個測試用例。每個測試用例第 1 行給出:第 1 個結點的地址;結點總個數,即正整數N (10?5??);以及正整數K (10?3??)。結點的地址是 5 位非負整數,NULL 地址用 ?1 表示。

接下來有 N 行,每行格式為:

Address Data Next

其中 Address 是結點地址;Data 是該結點保存的數據,為 [?10?5??,10?5??] 區間內的整數;Next 是下一結點的地址。題目保證給出的鏈表不為空。

輸出格式:

對每個測試用例,按鏈表從頭到尾的順序輸出重排後的結果鏈表,其上每個結點占一行,格式與輸入相同。

輸入樣例:

00100 9 10
23333 10 27777
00000 0 99999
00100 18 12309
68237 -6 23333
33218 -4 00000
48652 -2 -1
99999 5 68237
27777 11 48652
12309 7 33218

輸出樣例:

33218 -4 68237
68237 -6 48652
48652 -2 12309
12309 7 00000
00000 0 99999
99999 5 23333
23333 10 00100
00100 18 27777
27777 11 -1

  題解:這道題相比較前面那道鏈表元素反轉要簡單一些,記錄鏈表的方法仍采用之前的思想,直接把各個元素分類存儲在不同數組中,再依次輸出即可。

代碼如下:
 1 #include<iostream>
 2 #include<cstring>
 3 #define NUM 100000
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     int head, N, K, address, next, data, num1 = 0, num2 = 0, num3 = 0;
 9     scanf("%d %d %d", &head, &N, &K);
10     int a[NUM], b[NUM], c[NUM], d[NUM], e[NUM];
11     memset(a,-2
,NUM); 12 memset(b,-2,NUM); 13 memset(c,-2,NUM); 14 memset(d,-2,NUM); 15 memset(e,-2,NUM); 16 for( int i = 0; i < N; i++){ 17 int m=scanf("%d %d %d",&address, &data, &next); 18 a[address] = data; 19 b[address] = next; 20 } 21 address = head; 22 while(address != -1){ 23 if(a[address] < 0) 24 c[num1++] = address; 25 else if( a[address] >= 0 && a[address] <= K) 26 d[num2++] = address; 27 else 28 e[num3++] = address; 29 address = b[address]; 30 } 31 for(int i = 0; i < num2; i++) 32 c[num1++] = d[i]; 33 for(int i = 0; i < num3; i++) 34 c[num1++] = e[i]; 35 for( int i = 0; i < num1-1; i++) 36 printf("%05d %d %05d\n",c[i],a[c[i]],c[i+1]); 37 printf("%05d %d -1",c[num1-1], a[c[num1-1]]); 38 return 0; 39 }


PAT Basic 1075