Remove Duplicates from Sorted List II

原创 2015年07月08日 22:31:16

题目描述

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example

Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

链接地址

http://www.lintcode.com/en/problem/remove-duplicates-from-sorted-list-ii/

解法


ListNode * deleteDuplicates(ListNode *head) {
// write your code here
if (head == NULL) {
return head;
}
ListNode *dummyNode = new ListNode();
dummyNode->next = head;
ListNode *pre = dummyNode;
ListNode *cur = pre->next;
while (cur!= NULL && cur->next!= NULL) {
if (cur->val == cur->next->val) {
ListNode *temp = cur;
while (temp != NULL && temp->next != NULL && temp->val == temp->next->val) {
ListNode *del = temp->next;
temp->next = del->next;
delete del;
}
pre ->next = temp->next;
cur = pre->next;
delete temp;
} else {
pre = cur;
cur = cur->next;
}
}
ListNode *ret = dummyNode->next;
delete dummyNode;
return ret;
}

相关文章推荐

Remove Duplicates from Sorted List II 移除重复元素和其本身(重重)

题目: 点击打开链接 解答: 设置一个flag标志 代表当前元素是否是重复元素 如果是重复元素 在...

LeetCode82:Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct num...

Remove Duplicates from Sorted List II--LeetCode

题目: Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinc...

Remove Duplicates from Sorted List I,II

Remove Duplicates from Sorted List   Given a sorted linked list, delete all duplicates such that ea...

[LeetCode] Remove Duplicates from Sorted List II

给定一个已经排序的单链表,删除所有有相同数字的节点,只留下原始链表中的不同数字。...

【一天一道LeetCode】#82. Remove Duplicates from Sorted List II

一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目...

LeetCode - 82. Remove Duplicates from Sorted List II

这一道题目主要是链表的操作,一开始因为情况比较复杂,把自己绕晕了,所以没想到这道题目的解法,后来看了答案才觉得自己解起来确实很难解出。这道题目对于链表的操作比较复杂,所要考虑的情况也很多,最大的一个技...

leetcode_82_Remove Duplicates from Sorted List II

思路: 大致思路就是,遍历链表找出重复元素的子列并删除重复元素子列,当然,第一个元素开始有重复元素的话比较特种,需要特殊考虑。删除子列的过程稍微有点绕,题目倒是不难理解。...

[leetcode 82]Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numb...

LeetCode 82. Remove Duplicates from Sorted List II pre指针,首元素的处理

题目 题意 注意 思路 代码 结果题目 Given a sorted linked list, delete all nodes that have duplicate numbers, leav...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Remove Duplicates from Sorted List II
举报原因:
原因补充:

(最多只允许输入30个字)