Use set or not
#include "Solution.hpp"
class Solution;
class Node {
public:
Node (int val) {
this->val = val;
this->next = NULL;
}
int val;
Node *next;
friend class Solution;
};
// only for the 1st Node
//void initNode(Node *head,int n){
// head->val = n;
// head->next =NULL;
//}
class Solution {
public:
// add Node
void initList () {
head = new Node(0);
}
void addNode(int n) {
Node *newNode = new Node(n);
Node *cur = head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = newNode;
}
void PrintList(){
if (head->next == NULL) { // 如果first node指向NULL, 表示list沒有資料
cout << "List is empty.\n";
//cout <<"head "<<head->val<<endl;
return;
}
Node *cur = head; // 用pointer *current在list中移動
while (cur != NULL) { // Traversal
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
void deleteDuplicate() {
//Node* dummy = new Node(0);
//dummy->next = head;
Node* cur;
Node* newHead = head;
while (newHead != NULL && newHead->next != NULL) {
cur = newHead;
while (cur->next != NULL) {
if (cur->next->val == newHead->val) {
cur->next = cur->next->next;
} else {
cur = cur->next;
}
}
newHead = newHead->next;
}
}
void deleteDuplicateHash() {
Node* cur = head;
unordered_set<int> myset;
while (cur != NULL && cur->next != NULL) {
if (myset.find(cur->val) == myset.end()) {
myset.insert(cur->val);
}
while (myset.find(cur->next->val) != myset.end()) {
cur->next = cur->next->next;
}
cur = cur->next;
}
}
private:
Node* head;
};