From 1547926f858fd77389f75d9cda9431e1e7135549 Mon Sep 17 00:00:00 2001 From: pezy-pc Date: Mon, 19 Jan 2015 11:04:12 +0800 Subject: [PATCH] added 94. Remove Duplicates from Sorted List II --- .../README.md | 7 ++++ .../main.cpp | 25 +++++++++++ .../solution.h | 41 +++++++++++++++++++ 3 files changed, 73 insertions(+) create mode 100644 94. Remove Duplicates from Sorted List II/README.md create mode 100644 94. Remove Duplicates from Sorted List II/main.cpp create mode 100644 94. Remove Duplicates from Sorted List II/solution.h diff --git a/94. Remove Duplicates from Sorted List II/README.md b/94. Remove Duplicates from Sorted List II/README.md new file mode 100644 index 0000000..6319ed6 --- /dev/null +++ b/94. Remove Duplicates from Sorted List II/README.md @@ -0,0 +1,7 @@ +这道题没有太多可说的,属于基本题的扩展。 + +可以先参考前面的 [12. Remove Duplicates from Sorted List](../12. Remove Duplicates from Sorted List). + +而这道题多出的一点把戏在于,要把重复的数据删的干干净净。我的策略很简单,将重复的数据做一个标记,`isDuplicate`, 然后再删掉重复元素的基础上,最后给剩下那个光棍补上一刀。 + +虽然有点啰嗦,但是效率还过得去。 diff --git a/94. Remove Duplicates from Sorted List II/main.cpp b/94. Remove Duplicates from Sorted List II/main.cpp new file mode 100644 index 0000000..3caa839 --- /dev/null +++ b/94. Remove Duplicates from Sorted List II/main.cpp @@ -0,0 +1,25 @@ +#include "solution.h" +#include + +using namespace std; + +ListNode *create_linkedlist(std::initializer_list 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; +} + diff --git a/94. Remove Duplicates from Sorted List II/solution.h b/94. Remove Duplicates from Sorted List II/solution.h new file mode 100644 index 0000000..04a260e --- /dev/null +++ b/94. Remove Duplicates from Sorted List II/solution.h @@ -0,0 +1,41 @@ +#include + +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; + } +};