题解 | #删除有序链表中重复的元素-I#

删除有序链表中重复的元素-I

https://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 *  ListNode(int x) : val(x), next(nullptr) {}
 * };
 */

/*
class Solution {
  public:
    ListNode* deleteDuplicates(ListNode* head) {
        // 空链表
        if (head == nullptr) return nullptr;
        ListNode* dummy = new ListNode(-1);
        dummy->next = head;
        ListNode* pre = dummy;
        ListNode* cur = head;
        while (cur) {
            ListNode* next = cur->next;
            if (next == nullptr || cur->val != next->val) {
                cur->next = nullptr;
                pre->next = cur;
                pre = pre->next;
            }
            cur = next;
        }
        return dummy->next;
    }
};*/

/*
    pre
    ↓
dummy(-1) →  1  →  1  →  2  →  2  →  3  → NULL
             ↑     ↑
            cur   next

    pre
    ↓
dummy(-1) →  1  →  1  →  2  →  2  →  3  → NULL
             ↑     ↑
            cur   next


    pre
    ↓--------------+
dummy(-1) →  1  →  1  (x)  2  →  2  →  3  → NULL
                   |       ↑
                  NULL    next


                  pre
                   ↓
dummy(-1) →  1  →  1  (x)  2  →  2  →  3  → NULL
                           ↑     ↑
                          cur   next


                  pre
                   ↓
dummy(-1) →  1  →  1  (x)  2  →  2  →  3  → NULL
                                 ↑     ↑
                                cur   next

                  pre
                   ↓-------------+
dummy(-1) →  1  →  1  (x)  2  →  2  (x)  3  → NULL
                                 |       ↑
                                NULL    next

                                pre
                                 ↓
dummy(-1) →  1  →  1  (x)  2  →  2  (x)  3  → NULL
                                         ↑      ↑
                                        cur    next

                                pre
                                 ↓-------+
dummy(-1) →  1  →  1  (x)  2  →  2  (x)  3  (x)  NULL
                                         |        ↑
                                        NULL     next

                                        pre
                                         ↓
dummy(-1) →  1  →  1  (x)  2  →  2  (x)  3  (x)   NULL
                                                   ↑
                                                  cur

*/


class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        // 空链表
        if(head == nullptr) return nullptr;
        // 遍历指针
        ListNode* cur = head;
        // 指针当前和下一位不为空
        while(cur && cur->next) {
            // 如果当前与下一位相等则忽略下一位
            if(cur->val == cur->next->val) {
                cur->next = cur->next->next;
            }else{
                cur=cur->next;
            }
        }
        return head;
    }
};

全部评论

相关推荐

joe2333:怀念以前大家拿华为当保底的日子
点赞 评论 收藏
分享
废铁汽车人:秋招真是牛鬼蛇神齐聚一堂
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务