您的位置:首页 > 职场人生

面试金典--删除未排序链表重复节点

2014-06-15 11:33 357 查看
编写代码,删除未排序链表的重复节点

思路:

hash记录当前节点是否出现过

#include <iostream>
#include <string>
#include <fstream>
#include <map>
#include <algorithm>
#include <vector>
#include <ctime>
#include <bitset>

using namespace std;

template<typename T>
class Node
{
public:
Node<T> *next;
T data;

Node(T d):data(d),next(NULL){}
void appendToTail(T d)
{
Node<T> *end = new Node<T>(d);
Node<T> *n = this;
while(n->next != NULL)
{
n = n->next;
}
n->next = end;
}
};

int main()
{
Node<int> *head = new Node<int>(1);
int i;
for(i = 2 ; i < 6 ; ++i)
{
head->appendToTail(i);
}
//2.1
map<int,bool> nodesInList;
head->appendToTail(2);
map<int,bool>::iterator it;
Node<int> *prev = NULL;
Node<int> *headOrg = head;
while(head != NULL)
{
it = nodesInList.find(head->data);
if(it != nodesInList.end())
{
prev->next = head->next;
}
else
{
nodesInList[head->data] = true;
prev = head;
}
head = head->next;
}
while(headOrg != NULL)
{
cout<<headOrg->data<<endl;
headOrg = headOrg->next;
}
return 0;
}


扩展:没有缓冲区?那么只能O(N^2)了。上面相当于空间换时间
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: