标签:
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
思路:两个指针,一前一后,前面指针的值与后面指针的值相等就往前,直到不同,后指针的下一个节点指向前指针,然后继续。
注意一下边界:
尾部需要处理
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head)
{
if (!head || !head->next)
{
return head;
}
ListNode* forward = head->next;
ListNode* backward = head;
while (forward-> next!= NULL)
{
if (forward->val == backward->val)
{
forward = forward->next;
}
else
{
backward->next = forward;
backward = forward;
forward = forward->next;
}
}
if (backward->val == forward->val)
{
backward->next = NULL;
}
else
{
backward->next = forward;
}
return head;
}
};
Remove Duplicates from Sorted List
标签:
原文地址:http://www.cnblogs.com/flyjameschen/p/4341304.html