您的位置:首页 > 其它

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 
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: