删除排序链表中的重复元素

题目链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/
题目描述:
存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次 。
返回同样按升序排列的结果链表。

题解:


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

题目链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/
题目描述:
存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除链表中所有存在数字重复情况的节点,只保留原始链表中 没有重复出现的数字。返回同样按升序排列的结果链表。

题解:
注意点:

    // 1 --> 1 --> 1 --> 2 --> 3
    //     head  next
    //1.则需要移动next直到出现与当前head.value不相等的情况(含null)
    //2.并且此时的head已经不能要了,因为已经head是重复的节点
    //--------------else-------------
    //      1 --> 2 --> 3
    //     head  next
    //3.如果没有出现1的情况,则递归返回的节点就作为head的子节点
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(!head || !head->next)
            return head;
        ListNode *dummy = new ListNode(-1);
        dummy->next = head;
        ListNode *pre = dummy;
        ListNode *cur = head;
        while(cur != nullptr && cur->next != nullptr)
        {
            if(cur->val != cur->next->val)
            {
                pre = cur;
                cur = cur->next;
            }else
            {
               while(cur != nullptr && cur->val == pre->next->val)
               {
                   cur = cur->next;
               }
               pre->next = cur;
            }
        }
        return dummy->next;

    }
};
posted @ 2021-06-10 18:06  张宵  阅读(54)  评论(0编辑  收藏  举报