【Leetcode长征系列】Remove Duplicates from Sorted List II
2014-08-03 19:52
357 查看
原题:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving onlydistinct numbers from the original list.
For example,
Given
Given
代码:
需要注意的特殊情况:
1. {1}
2. {1->2}
3. {1->1->2}
要注意pre的初始值!NULL最佳,本次情况下不适合用head作为初始值。
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving onlydistinct numbers from the original list.
For example,
Given
1->2->3->3->4->4->5, return
1->2->5.
Given
1->1->1->2->3, return
2->3.
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *deleteDuplicates(ListNode *head) { if(head==NULL) return NULL; if(head->next==NULL) return head; ListNode *tmp = head, *pre; pre = NULL; while(tmp){ if (tmp->val==tmp->next->val) { ListNode *s = tmp->next; while (s->next!=NULL && s->val==s->next->val){ s = s->next; } if(pre==NULL){ if(s->next!=NULL){ head = s->next; tmp = head; } else return NULL; } else{ pre->next = s->next; tmp = pre->next; } } else { pre = tmp; tmp = tmp->next; } if (tmp==NULL || tmp->next==NULL) break; } return head; } };
需要注意的特殊情况:
1. {1}
2. {1->2}
3. {1->1->2}
要注意pre的初始值!NULL最佳,本次情况下不适合用head作为初始值。
相关文章推荐
- 【Leetcode长征系列】Remove Duplicates from Sorted Array II
- leetcode系列(3)--Remove Duplicates from Sorted List II
- 【Leetcode长征系列】Remove Duplicates from Sorted List
- [leetcode刷题系列]Remove Duplicates from Sorted List II
- 算法系列——Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- LeetCode_Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- [LeetCode]Remove Duplicates from Sorted List II
- Leetcode: Remove Duplicates from Sorted List II
- leetcode 38: Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode 70] 82 Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- Remove duplicates from sorted list II
- [Leetcode] Remove Duplicates from Sorted List II