[LeetCode] 83. Remove Duplicates from Sorted List

Posted wengle

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 83. Remove Duplicates from Sorted List相关的知识,希望对你有一定的参考价值。

1. 原题链接:https://leetcode.com/problems/remove-duplicates-from-sorted-list/

2. 解题思路

  1. 删除链表节点会涉及到两个指针:prev指针和cur指针

3. 算法

  1. prev指针和cur指针分别指向前两个节点
  2. 从cur指向的节点开始循环遍历,当prev和cur的val相同时,将prev指向cur->next节点;否则prev指向cur的节点

4. 实现

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(head == NULL) return head;
        
        ListNode *prev = head;
        for(ListNode *cur = prev->next; cur != NULL; cur = cur->next){
            if(prev->val == cur->val){
                prev->next = cur->next;
            }else{
                prev = cur;
            }
        }
        return head;
    }
};

以上是关于[LeetCode] 83. Remove Duplicates from Sorted List的主要内容,如果未能解决你的问题,请参考以下文章

leetcode83-Remove Duplicates from Sorted List

[LeetCode] 83. Remove Duplicates from Sorted List

LeetCode83 Remove Duplicates from Sorted List

LeetCode 83 Remove Duplicates from Sorted List

LeetCode:83.Remove Duplicates from Sorted List

leetcode83 Remove Duplicates from Sorted List