面试金典--删除未排序链表重复节点
2014-06-15 11:33
357 查看
编写代码,删除未排序链表的重复节点
思路:
hash记录当前节点是否出现过
扩展:没有缓冲区?那么只能O(N^2)了。上面相当于空间换时间
思路:
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)了。上面相当于空间换时间
相关文章推荐
- 删除排序链表的所有重复节点
- 【LeetCode-面试算法经典-Java实现】【083-Remove Duplicates from Sorted List(排序的单链表中删除重复的结点)】
- 删除排序链表的的重复节点
- 【LeetCode-面试算法经典-Java实现】【082-Remove Duplicates from Sorted List II(排序链表中删除重复元素II)】
- 删除排序链表的重复节点
- 删除排序链表中重复的节点 递归方式
- 给定一个排序的链表,删除所有具有重复数字的节点,从原始列表中只留下不同的数字。
- 面试金典--删除链表某个节点,只能访问该节点
- LeetCode 刷题: 删除已排序链表中的重复节点
- 删除链表中的重复节点
- 单链表的建立、测长、打印、删除节点、插入节点、排序、逆转
- 删除单向链表中重复的节点
- 剑指offer 57 - 删除链表中重复的节点
- [华为机试练习题]24.删除链表中的重复节点、剩余节点逆序输出
- LeetCode(Remove Duplicates from Sorted List) 两道删除排序链表中重复数字
- 合并两个排序的链表及简单链表的一些操作(添加节点、删除节点)
- leetCode 82.Remove Duplicates from Sorted List II (删除排序链表的重复II) 解题思路和方法
- 删除链表中的重复节点、剩余节点逆序输出
- 【链表】删除链表中连续重复的节点
- 程序员面试金典(4)移除未排序链表的重复节点