【leetcode】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.

Return the linked list sorted as well.


思路:
在原链表head的前面,加一个super head,这样操作起来更方便一些。我运气不错,提交一次就通过了。


代码实现:
注意:代码没有考虑内存泄漏问题,按理讲是应该考虑的。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    
    void deleteNextAllSameVal(ListNode *pre){
        int val = pre->next->val;
        while (pre->next && pre->next->val == val){
            pre->next = pre->next->next;
        }
    }
    ListNode* deleteDuplicates(ListNode* head) {
        if (head == nullptr || head->next == nullptr){
            return head;
        }        
        
        ListNode *superHead = new ListNode();
        superHead->next = head;
        ListNode *pre = superHead;
        ListNode *cur = head;
        
        while (cur && cur->next){
            if (cur->val == cur->next->val){
                deleteNextAllSameVal(pre);
                cur = pre->next;
            }else{
                pre = pre->next;
                cur = cur->next;
            }
        }
        
        return superHead->next;
    }
};

discuss:

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (head == NULL) return NULL;
        ListNode *FakeHead = new ListNode;
        FakeHead->next = head;
        ListNode *pre = FakeHead;;
        ListNode *cur = head;
        
        while (cur != NULL){
            while (cur->next != NULL && cur->val == cur->next->val){ // cur会停在最后一个重复元素上
                cur = cur->next;
            }
            if (pre->next == cur){ // cur没有动
                pre = pre->next; // pre后移
            }else{
                pre->next = cur->next; // 直接把全部重复元素都跳过了
            }
            cur = cur->next;
        }
        
        return FakeHead->next;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值