[Leetcode] Remove duplicate from sorted list ii 从已排序的链表中删除重复结点
2017-06-14 14:50
615 查看
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given1->2->3->3->4->4->5, return1->2->5.
Given1->1->1->2->3, return2->3.
这题和Remove duplicate from sorted list的区别在于,本题中,只要结点只要出现重复则该值相等的结点都要删除,上题中留一个不删。
思路:这里有可能有修改表头(如:1->1->1>2>3),一般修改表头的题目都会需要一个辅助指针,所以要新建一个结点。遍历链表,遇到相等的相邻结点,直接继续遍历;遇到不相等的两相邻结点时,若pre->next=cur说明cur没有重复的,pre=pre->next即可,若是不等于说明,可能有重复,则,pre连接cur但是pre不移动,需重新进入循环检验是否没有重复(没有重复时,pre->next=cur),直到没有重复结点。源代码
主要的思想是:保持前指针pre不动,因为pre没有重复,所以用其next去和后面的比较。当遇到值不相等时,判断中间是否有重复,即pre->next=cur(这里判断cur是否为pre的后缀,不是值的判断),没有,pre移动,有,则pre不动,但和后面的连接起来,继续重复。
1 class Solution { 2 public: 3 ListNode *deleteDuplicates(ListNode *head) 4 { 5 if(head==NULL) return head; 6 7 ListNode *newList=new ListNode(-1); 8 newList->next=head; 9 ListNode *pre=newList; 10 ListNode *cur=head; 11 12 while(cur) 13 { 14 while(cur->next&&pre->next->val==cur->next->val) 15 { 16 cur=cur->next; 17 } 18 19 if(pre->next==cur) //想明白!不是值。 20 pre=pre->next; 21 else 22 { 23 pre->next=cur->next; 24 } 25 26 cur=cur->next; 27 } 28 return newList->next; 29 } 30 };
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【082-Remove Duplicates from Sorted List II(排序链表中删除重复元素II)】
- 【LeetCode-面试算法经典-Java实现】【083-Remove Duplicates from Sorted List(排序的单链表中删除重复的结点)】
- LeetCode | Remove Duplicates from Sorted List II(删除链表中重复结点2)
- [Leetcode] Remove duplicates from sorted list 从已排序的链表中删除重复元素
- LeetCode(Remove Duplicates from Sorted List) 两道删除排序链表中重复数字
- leetcode——Remove Duplicates from Sorted List II 删除排序字符串中重复字符(AC)
- [LeetCode] Remove Duplicates from Sorted List 删除排序链表中的重复元素
- [Lintcode]Remove Duplicates from Sorted List II 删除排序链表中的重复数字 II
- Leetcode Remove Duplicates from Sorted List II 删除链表中重复的元素II
- leetcode(83)—— 删除已排序链表重复元素(Remove Duplicates from Sorted List)
- Remove Duplicates from Sorted List II (删除排序链表的重复II)
- LeetCode | Remove Duplicates from Sorted List(删除链表中重复的数据)
- (LeetCode)Remove Duplicates from Sorted List --- 链表中删除重复元素
- [Leetcode] Remove duplicates from sorted array ii 从已排序的数组中删除重复元素
- Leetcode:Remove Duplicates from Sorted List 删除单链表中重复的节点
- [LeetCode]Merge Two Sorted Lists & Remove Duplicates from Sorted List 两个有序链表合并为一个&删除链表重复元素
- LeetCode 83 Remove Duplicates from Sorted List(从已排序链表中移除重复元素)(*)
- LeetCode-Remove Duplicates from Sorted List II-从有序链表中移除重复元素-链表操作
- [LeetCode] Remove Duplicates from Sorted Linked List 从排序链表中去掉重复值
- Remove Duplicates from Sorted List II 链表移除重复值@LeetCode