題目
思路:
- 先把題目中的鏈表讀進內存
- 創建兩個新鏈表listA, listB
- 遍歷原鏈表,把重復的放進listB,不重復的放進listA。放的時候,注意處理一下后繼next中存的值。
- 分別打印兩個分離的鏈表listA,listB,注意補全5位address的前導0
題解 C++
每次提交結果不完全一樣,有時候后兩個測試點運行超時,有時候全部AC。
實際比賽的時候,也要多試幾次(上次就是,提交多次,結果有微小差別)。
#include<iostream>
#include<math.h>
#include<iomanip>
#define SIZE 10000
using namespace std
;
class Node
{
public
:int addr
= -1;int key
; int next
= -1;bool isSame
= false
;
};
int main() {Node list
[SIZE
]; int firstNotSame
, total
;cin
>> firstNotSame
>> total
;int addr
;for (int i
= 0; i
< total
; i
++) {cin
>> addr
;list
[addr
].addr
= addr
;cin
>> list
[addr
].key
>> list
[addr
].next
;}Node listA
[SIZE
];int sizeA
= 0;Node listB
[SIZE
];int sizeB
= 0;bool hasKey
[10000] = { false
};Node cur
= list
[firstNotSame
];while (true
) {if (!hasKey
[abs(cur
.key
)]) {hasKey
[abs(cur
.key
)] = true
;if (sizeA
!= 0) {listA
[sizeA
- 1].next
= cur
.addr
;}listA
[sizeA
] = cur
;listA
[sizeA
].next
= -1;sizeA
++;}else {if (sizeB
!= 0) {listB
[sizeB
- 1].next
= cur
.addr
;}listB
[sizeB
] = cur
;listB
[sizeB
].next
= -1;sizeB
++;}if (cur
.next
== -1) {break;}else {cur
= list
[cur
.next
];}}for (int i
= 0; i
< sizeA
; i
++) {cout
<< setw(5) << setfill('0') << listA
[i
].addr
<< " ";cout
<< listA
[i
].key
<< " ";if (listA
[i
].next
== -1)cout
<< "-1\n"; else cout
<< setw(5) << setfill('0') << listA
[i
].next
<< endl
;}for (int i
= 0; i
< sizeB
; i
++) {cout
<< setw(5) << setfill('0') << listB
[i
].addr
<< " ";cout
<< listB
[i
].key
<< " ";if (listB
[i
].next
== -1)cout
<< "-1\n"; else cout
<< setw(5) << setfill('0') << listB
[i
].next
<< endl
;}system("pause");
}
總結
以上是生活随笔為你收集整理的【PAT甲级 链表去重】1097 Deduplication on a Linked List (25 分) C++ 全部AC的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。