fork download
  1. //Code by Shubham Joshi
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. struct Node
  6. {
  7. int data;
  8. Node* next;
  9. };
  10. Node *newNode(int data)
  11. {
  12. Node *new_node = new Node;
  13. new_node->data = data;
  14. new_node->next = NULL;
  15. return new_node;
  16. }
  17. void print(Node *root)
  18. {
  19. Node *temp = root;
  20. while(temp!=NULL)
  21. {
  22. cout<<temp->data<<" ";
  23. temp=temp->next;
  24. }
  25. }
  26. Node* removeDuplicates(Node *root);
  27. int main() {
  28. // your code goes here
  29. int T;
  30. cin>>T;
  31.  
  32. while(T--)
  33. {
  34. int K;
  35. cin>>K;
  36. Node *head = NULL;
  37. Node *temp = head;
  38.  
  39. for(int i=0;i<K;i++){
  40. int data;
  41. cin>>data;
  42. if(head==NULL)
  43. head=temp=newNode(data);
  44. else
  45. {
  46. temp->next = newNode(data);
  47. temp=temp->next;
  48. }
  49. }
  50. Node *result = removeDuplicates(head);
  51. print(result);
  52. cout<<endl;
  53. }
  54. return 0;
  55. }
  56.  
  57. /*The structure of linked list is the following
  58. struct Node
  59. {
  60. int data;
  61. Node* next;
  62. };*/
  63. Node *removeDuplicates(Node *root)
  64. {
  65. // your code goes here
  66. struct Node* curr = root,*prev = NULL;
  67. while(curr)
  68. {
  69. if(prev==NULL)
  70. {
  71. prev = curr;
  72. curr = curr->next;
  73. }
  74. else if(curr->data!=prev->data)
  75. prev = curr;
  76. else
  77. {
  78. prev->next = curr->next;
  79. delete curr;
  80. curr = prev->next;
  81. }
  82. }
  83. return root;
  84. }
  85.  
Success #stdin #stdout 0s 15240KB
stdin
3
4
2 2 4 5
5
2 2 2 2 2
7
11 11 11 21 43 43 60 
stdout
2 -525390784 -525390752 
2 
11 -525386608 -525386640 -525386512 -525386480