Remove Duplicates from Sorted List II问题及解法
2017-08-04 10:20
344 查看
问题描述:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
示例:
Given
Given
问题分析:
对每一个元素进行判断,如它和前一个和后一个元素均不相等,则保留,否则删除掉。
过程详见代码:
/**
* 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) {
ListNode *ptr = NULL, *res = NULL, *last = NULL;
if (head == NULL) return head;
while (head)
{
if (head->next== NULL || head->val != head->next->val)
{
if (last == NULL)
{
ptr = head;
res = head;
}
else if (head->val != last ->val)
{
if (ptr == NULL)
{
ptr = head;
res = head;
}
else
{
ptr->next = head;
ptr = ptr->next;
}
}
}
last = head;
head = head->next;
}
if(ptr) ptr->next = NULL;
return res;
}
};
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
示例:
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) {
ListNode *ptr = NULL, *res = NULL, *last = NULL;
if (head == NULL) return head;
while (head)
{
if (head->next== NULL || head->val != head->next->val)
{
if (last == NULL)
{
ptr = head;
res = head;
}
else if (head->val != last ->val)
{
if (ptr == NULL)
{
ptr = head;
res = head;
}
else
{
ptr->next = head;
ptr = ptr->next;
}
}
}
last = head;
head = head->next;
}
if(ptr) ptr->next = NULL;
return res;
}
};
相关文章推荐
- Remove Duplicates from Sorted List II——简单的指针问题
- Remove Duplicates from Sorted Array II问题及解法
- Remove Duplicates from Sorted List问题及解法
- [leetcode]82 Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II (read and think again!)
- Remove Duplicates from Sorted List II 解答
- Remove Duplicates from Sorted List II
- 【LeetCode练习题】Remove Duplicates from Sorted List II
- [LeetCode80]Remove Duplicates from Sorted List II
- leetcode笔记--Remove Duplicates from Sorted List II
- LeetCode OJ - Remove Duplicates from Sorted List II
- [leetcode][list] Remove Duplicates from Sorted List II
- LeetCode: Remove Duplicates from Sorted List II [083]
- Leetcode-82: Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II
- [leetcode笔记] Remove Duplicates from Sorted List II
- LintCode - Remove Duplicates from Sorted List II Show result
- 82. Remove Duplicates from Sorted List II(Python3)
- [LintCode] Remove Duplicates from Sorted List II
- 【LeetCode】Remove Duplicates from Sorted List II