82. 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.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
解题思路:
/*
执行用时 : 20 ms, 在Remove Duplicates from Sorted List II的C提交中击败了29.95% 的用户
内存消耗 : 7.6 MB, 在Remove Duplicates from Sorted List II的C提交中击败了38.30% 的用户
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head){
//特殊情况提前讨论
if(head == NULL || head->next == NULL){
return head;
}
struct ListNode* L = (struct ListNode*)malloc(sizeof(struct ListNode));
L->next = head;
struct ListNode* p = head->next;//工作指针,遍历链表
struct ListNode* pre = head;//pre指向某数值第一次出现时的结点
struct ListNode* tail = L;//指向需返回结点的尾节点,用于收集需返回的结点
while(p != NULL){
if(p->val == pre->val){
//由于是有序的,所以先找出一个不与前面结点值相等的结点
while(p != NULL && p->val == pre->val){
p = p->next;
}
tail->next = p;//删除重复元素,注意,此时并没用释放结点,只是简单地断开了链接
pre = p;//指向新的数值,此数值第一次出现
if(p){//由于前面的while,所以需重新判断p为不为空
p = p->next;
}
}
else{
//代表pre结点不是重复元素,链接到返回链表区
//此时pre指向的结点值是第一次出现,p为其后继,tail为其前驱
p = p->next;
pre = pre->next;
tail = tail->next;
}
}
return L->next;
}
/*
对于原链表的尾结点。当它与它的前驱相等时,程序执行if条件,p指向它的next,此时为NULL,再tail = p;当它与前驱不相等时,程序执行else,p指向它的next,为NULL,tail指向其前驱,pre指向p(即尾节点),此时tail与最后一个结点未断开,最后一个结点也加入了返回链表区
*/
/*
最后执行的输入:
[1,1]
*/
LeetCode 83. Remove Duplicates from Sorted List(删除排序链表中的重复元素) -- c语言