Skip to content

Commit

Permalink
added 94. Remove Duplicates from Sorted List II
Browse files Browse the repository at this point in the history
  • Loading branch information
pezy committed Jan 19, 2015
1 parent 574a9c7 commit 1547926
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
7 changes: 7 additions & 0 deletions 94. Remove Duplicates from Sorted List II/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
这道题没有太多可说的,属于基本题的扩展。

可以先参考前面的 [12. Remove Duplicates from Sorted List](../12. Remove Duplicates from Sorted List).

而这道题多出的一点把戏在于,要把重复的数据删的干干净净。我的策略很简单,将重复的数据做一个标记,`isDuplicate`, 然后再删掉重复元素的基础上,最后给剩下那个光棍补上一刀。

虽然有点啰嗦,但是效率还过得去。
25 changes: 25 additions & 0 deletions 94. Remove Duplicates from Sorted List II/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#include "solution.h"
#include <iostream>

using namespace std;

ListNode *create_linkedlist(std::initializer_list<int> lst)
{
auto iter = lst.begin();
ListNode *head = lst.size() ? new ListNode(*iter++) : NULL;
for (ListNode *cur=head; iter != lst.end(); cur=cur->next)
cur->next = new ListNode(*iter++);
return head;
}

int main()
{
Solution s;
ListNode *head = s.deleteDuplicates(create_linkedlist({1,1,2,2,3,4}));
for (ListNode *cur=head; cur; cur=cur->next)
std::cout << cur->val << "->";
std::cout << "\b\b " << std::endl;

return 0;
}

41 changes: 41 additions & 0 deletions 94. Remove Duplicates from Sorted List II/solution.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#include <cstddef>

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if (head == NULL) return head;
ListNode preHead(0);
preHead.next = head;
ListNode *pre = &preHead;
bool isDuplicate = false;
ListNode *p = head;
while (p->next)
if (p->val == p->next->val) {
ListNode *next = p->next->next;
delete p->next;
p->next = next;
isDuplicate = true;
} else if (isDuplicate) {
ListNode *next = p->next;
delete p;
p = next;
pre->next = p;
isDuplicate = false;
} else {
pre = p;
p = p->next;
}
if (isDuplicate) {
ListNode *next = p->next;
delete p;
pre->next = next;
}
return preHead.next;
}
};

0 comments on commit 1547926

Please sign in to comment.