Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
<pre name="code" class="cpp">class Solution
{
public:
ListNode *deleteDuplicates(ListNode *head)
{
if (head == NULL||head->next == NULL)//当头结点为空或者头结点指向的下一个结点为空时返回头结点
return head;
ListNode *LNpPos1 = head, *LNpPos2 = head->next, *LNpMiddle = NULL;//初始化两个指针为头结点和头结点指向的下一个结点
LNpPos1->next = NULL;
while (LNpPos2 != NULL)//如果第二个指针指向不为空则继续向后遍历
{
if (LNpPos1->val == LNpPos2->val)//如果第二个指针处结点的值和当前处理过的数列最后一个结点的值相同则将第二个指针向后移
{
LNpMiddle = LNpPos2;
LNpPos2 = LNpPos2->next;
free(LNpMiddle);
}
else
{
LNpPos1->next = LNpPos2;
LNpPos1 = LNpPos1->next;
LNpPos2 = LNpPos2->next;
LNpPos1->next = NULL;
}
}
return head;
}
};