【Leetcode长征系列】Remove Duplicates from Sorted List II
来源:互联网 发布:留学低龄化数据 编辑:程序博客网 时间:2024/04/30 15:22
原题:
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作为初始值。
0 0
- 【Leetcode长征系列】Remove Duplicates from Sorted List II
- 【Leetcode长征系列】Remove Duplicates from Sorted Array II
- 【Leetcode长征系列】Remove Duplicates from Sorted List
- leetcode系列(66)Remove Duplicates from Sorted List,Remove Duplicates from Sorted List II
- [leetcode刷题系列]Remove Duplicates from Sorted List II
- 【Leetcode长征系列】Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode]Remove Duplicates from Sorted List II
- [leetcode]Remove Duplicates from Sorted List II
- LeetCode-Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- LeetCode - Remove Duplicates from Sorted List II
- 【学习记录】面向对象的基本概念4
- 2014-08-03 日记
- 优先队列版子
- 【liunx命令学习】nc扫描远程端口
- 算法竞赛入门经典-第三章源代码
- 【Leetcode长征系列】Remove Duplicates from Sorted List II
- uva674 - Coin Change(完全背包)
- 九度OJ——1384
- [学习小结]Ajax基本操作_XML格式&&在jQuery中如何操作
- Linux网络编程(七) 套接字选项
- 【hiho一下】第五周 数字三角形
- Win32应用程序窗口无法弹出
- 数据库视频总结
- 牛顿迭代法求开方值