2.1 Write code to remove duplicates from an unsorted linked list.
FOLLOW UP
How would you solve this problem if a temporary buffer is not allowed?
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
void deleteDups(ListNode *head) {
if (head) {
map<int, bool> table;
ListNode *current = head;
ListNode *prevous = NULL;
while (current) {
if (table.find(current->val) != table.end()) {
prevous->next = current->next;
} else {
table.insert(pair<int, bool>(current->val, true));
prevous = current;
}
current = current->next;
}
}
}
Follow up:
void deleteDups(ListNode *head) {
if (head) {
ListNode *current = head;
while (current) {
ListNode *runner = current;
while (runner->next) {
if (current->val == runner->next->val) {
runner->next = runner->next->next;
} else {
runner = runner->next;
}
}
current = current->next;
}
}
}