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;
}
}
}
本文介绍了一种从无序链表中去除重复元素的方法,并提供了两种实现方式:一种使用辅助哈希表来提高效率;另一种则完全不使用额外空间,通过双指针技巧完成任务。
454

被折叠的 条评论
为什么被折叠?



