Skip to content

Instantly share code, notes, and snippets.

@ThunderXu
Created February 24, 2013 09:58
Show Gist options
  • Save ThunderXu/5023278 to your computer and use it in GitHub Desktop.
Save ThunderXu/5023278 to your computer and use it in GitHub Desktop.
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?
#include <iostream>
#include <hash_set>
#include <string>
class Node
{
public:
int data;
Node* next;
};
void Input(Node*, Node*);
void Output(Node*, Node*);
void DelDuplication1(Node*, Node*);
void DelDuplication2(Node*, Node*);
void Del(Node*, Node*);
int main()
{
Node *head = new Node();
Node *end = new Node();
Input(head,end);
DelDuplication2(head,end);
Output(head,end);
Del(head,end);
return 0;
}
void DelDuplication1(Node* head, Node* end)
{
using namespace __gnu_cxx;
hash_set<int> hashset;
Node *current = head;
while(current->next!=end)
{
Node *former = current;
current = current->next;
if(hashset.find(current->data)==hashset.end())
{
hashset.insert(current->data);
}
else
{
former->next = current->next;
delete current;
current = former;
}
}
}
void DelDuplication2(Node* head, Node* end)
{
Node *current = head;
while(current->next!=end)
{
current = current->next;
Node *iter = current;
while(iter->next!=end)
{
Node *former = iter;
iter = iter->next;
if(iter->data==current->data)
{
former->next = iter->next;
delete iter;
iter = former;
}
}
}
}
//input the linked list
void Input(Node* head, Node* end)
{
using namespace std;
int num;
Node *current = head;
while(cin>>num)
{
current->next = new Node();
current = current->next;
current->data = num;
}
current->next = end;
}
void Output(Node* head, Node* end)
{
using namespace std;
Node *current = head;
while(current->next!=end)
{
current = current->next;
cout<<current->data<<" ";
}
cout<<endl;
}
void Del(Node* head, Node* end)
{
Node *current = head;
while(current->next!=end)
{
Node* former = current;
current = current->next;
former->next = current->next;
delete current;
current = former;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment