力扣82.删除排序链表中的重复元素II

题目:

给定一个已排序的链表的头 head , 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。

示例一:

输入:head = [1,2,3,3,4,4,5]
输出:[1,2,5]

示例二:

输入:head = [1,1,1,2,3]
输出:[2,3]

提示:

    链表中节点数目在范围 [0, 300] 内 -100 <= Node.val <= 100 题目数据保证链表已经按升序 排列

思路:

思路就是通过循环来实现重复元素结点的删除,有两种方式来实现,一种是通过快慢指针来实现,一种是通过当前结点来实现

快慢指针:

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(head == nullptr){
            return head;
        }
        ListNode* p = new ListNode(0);//虚头节点
        p->next = head;
        ListNode *slow, *fast;
        head = p;
        while(p->next != nullptr){
            slow = p->next;
            fast = slow;
            while(fast->next != nullptr && fast->next->val == slow->val){
                fast = fast->next;
            }
            if(slow == fast){
                p = p->next;
            }
            else{
                p->next = fast->next;
            }
        }
        return head->next;
    }
};

当前结点:

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(head == nullptr){
            return head;
        }
        ListNode* p = new ListNode(0);//虚头节点
        p->next = head;
        ListNode* cur = p;;
        while(cur->next && cur->next->next){
            if(cur->next->val == cur->next->next->val){//找到值相同的结点
                int temp = cur->next->val;//临时变量储存下重复的值
                while(cur->next && cur->next->val == temp){//删除重复结点
                    cur->next = cur->next->next;
                }
            }
            else{
                cur = cur->next;
            }
        }
        return p->next;
    }
};
经验分享 程序员 微信小程序 职场和发展