Remove Duplicates from Sorted List II
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.
Linked List
中等
题目意思是给定一个排好序的单链表,删除所有重复的节点,包含重复的节点自身,返回新的链表。做法是创建一个节点,用来记录最终的头结点。
struct ListNode* deleteDuplicates(struct ListNode* head)
{
struct ListNode *p, *q, *ret;
struct ListNode * list = (struct ListNode *)malloc(sizeof(struct ListNode));
p = head;
q = list;
while(p)
{
if(p->next && (p->val == p->next->val))
{
while(p->next && (p->val == p->next->val))
{
p = p->next;
}
}
else
{
q->next = p;
q = p;
}
p = p->next;
}
if(q)
q->next = NULL;
ret = list->next;
if(list)
free(list);
return ret;
}