Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
这个题目要求在原链表中只剩下非重复的部分,与Remove Duplicates from Sorted List很相似,但是这里不要重复的部分,之前是至少保留一个,因此在处理的时候有部分区别,需要用一个新的节点作为头结点,因为可能没有节点满足条件。
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head == NULL)
return head;
ListNode *front = new ListNode(-1);
ListNode* temp = front;
ListNode *p = head;
while(p != NULL)
{
ListNode *q = p->next;
if((q != NULL && q->val != p->val) || q == NULL)
{
front->next = p;
front = front->next;
}else
{
q = q->next;
while(q != NULL && q->val == p->val)
q = q->next;
}
p = q;
}
front->next = NULL;
return temp->next;
}
};