Given a singly linked list L with integer keys, you are supposed to remove the nodes with duplicated absolute values of the keys. That is, for each value K, only the first node of which the value or absolute value of its key equals K will be kept. At the mean time, all the removed nodes must be kept in a separate list. For example, given L being 21→-15→-15→-7→15, you must output 21→-15→-7, and the removed list -15→15.

Input Specification:

Each input file contains one test case. For each case, the first line contains the address of the first node, and a positive N (≤105) which is the total number of nodes. The address of a node is a 5-digit nonnegative integer, and NULL is represented by −1.

Then N lines follow, each describes a node in the format:

  1. Address Key Next

where Address is the position of the node, Key is an integer of which absolute value is no more than 104, and Next is the position of the next node.

Output Specification:

For each case, output the resulting linked list first, then the removed list. Each node occupies a line, and is printed in the same format as in the input.

Sample Input:

  1. 00100 5
  2. 99999 -7 87654
  3. 23854 -15 00000
  4. 87654 15 -1
  5. 00000 -15 99999
  6. 00100 21 23854

Sample Output:

  1. 00100 21 23854
  2. 23854 -15 99999
  3. 99999 -7 -1
  4. 00000 -15 87654
  5. 87654 15 -1

思路

本题属于静态链表题型,所以我们可以这样处理:

  1. 用两个向量firstShownremovedList分别记录:

    • 第一次出现的元素;
    • 被删除的元素;
  2. 用哈希表记录元素出现的次数;
  3. 注意第二个向量可能是空的;
  4. 打印输出;

代码

  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4. using namespace std;
  5. typedef struct node_st {
  6. int key;
  7. int next;
  8. } node_st;
  9. node_st myNode[100001];
  10. int hash_table[10001];
  11. int main() {
  12. int HEAD(0), N(0);
  13. cin >> HEAD >> N;
  14. // Read list
  15. for(int i = 0; i < N; i++) {
  16. int _addr;
  17. cin >> _addr;
  18. cin >> myNode[_addr].key >> myNode[_addr].next;
  19. }
  20. // Deduplication
  21. vector<int> firstShown;
  22. vector<int> removedList;
  23. for(int i = HEAD; i != -1; i = myNode[i].next) {
  24. int absKey = abs( myNode[i].key );
  25. if( hash_table[ absKey ] == 0 ) { // first apperance
  26. hash_table[ absKey ]++;
  27. firstShown.push_back(i);
  28. } else {
  29. removedList.push_back(i);
  30. }
  31. }
  32. // Display result
  33. for(int i = 0; i < firstShown.size(); i++) {
  34. if( i + 1 < firstShown.size() )
  35. printf("%05d %d %05d\n", firstShown[i], myNode[firstShown[i]].key, firstShown[i + 1]);
  36. else
  37. printf("%05d %d -1\n", firstShown[i], myNode[firstShown[i]].key);
  38. }
  39. if(removedList.size()) {
  40. for(int i = 0; i < removedList.size(); i++) {
  41. if( i + 1 < removedList.size() )
  42. printf("%05d %d %05d\n", removedList[i], myNode[removedList[i]].key, removedList[i + 1]);
  43. else
  44. printf("%05d %d -1\n", removedList[i], myNode[removedList[i]].key);
  45. }
  46. }
  47. return 0;
  48. }