LeetCode 83. Remove Duplicates from Sorted List(删除排序链表中的重复元素) -- c语言

 83. Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

解题思路:

遍历链表,当前结点与前驱结点值相同时,将前驱结点的next指向当前结点的next

1.双指针法:

/*
执行用时 : 8 ms, 在Remove Duplicates from Sorted List的C提交中击败了98.78% 的用户
内存消耗 : 7.8 MB, 在Remove Duplicates from Sorted List的C提交中击败了5.21% 的用户
*/
/*
添加了特殊情况的head->next == NULL,执行时间从8ms到4ms
执行用时 : 4 ms, 在Remove Duplicates from Sorted List的C提交中击败了99.88% 的用户
内存消耗 : 7.8 MB, 在Remove Duplicates from Sorted List的C提交中击败了5.21% 的用户
*/
/**
 * 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* p = head->next;
    struct ListNode* q = head;
    while(p!=NULL){
        if(p->val == q->val){
            q->next = p->next;
            free(p);
            p = q->next;
        }
        else{
            p = p->next;
            q = q->next;
        }
    }
    return head;

}

2.单指针法:

struct ListNode* deleteDuplicates(struct ListNode* head){
    
    if(head == NULL || head->next == NULL){
        return head;
    }
    
    struct ListNode* p = head;
    while(p!=NULL && p->next != NULL){
        if(p->next->val == p->val){
            p->next = p->next->next;
        }
        else{
            p = p->next;
        }
    }
    return head;

}

后记:

对特殊情况的考虑可以减少执行时间

 

LeetCode 82. Remove Duplicates from Sorted List II(删除排序链表中的重复元素 II)--c语言

https://blog.csdn.net/d_benhua/article/details/91159647

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值