LeetCode83

题目链接

https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/

题目分析

  • 链表已排序

题解一:迭代

思路

遍历链表,如果发现重复元素就删除。

注意发现重复时遍历链表用的指针不要后移,不重复时才后移。

代码

// Problem: LeetCode 83
// URL: https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/description/
// Tags: Linked List Recursion Iteration
// Difficulty: Easy

#include <iostream>
using namespace std;

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(nullptr == head){return head;}
        ListNode *next = nullptr;
        ListNode* ret = head; // 用于返回
        while(head->next !=  nullptr){
            next = head->next;
            // 元素重复
            if (head->val == next->val){
                head->next = next->next;
                delete next;
            }
            // 元素未重复
            else{
                head = next;
            }
        }
        return ret;
    }
};

int main()
{
    // system("pause");
    return 0;
}

题解二:递归

关于递归

又摸到一个递归函数套路(有可能仅针对这道题):

  1. 递归出口(包括边界)
  2. 递归调用
  3. 手工拼接?(这一步可能直接融合到第二步)

思路

  • 递归函数的功能是将一个链表去重
  • 思路是取出head然后剩下的链表通过递归去重,然后手动去重

代码

// Problem: LeetCode 83
// URL: https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/description/
// Tags: Linked List Recursion Iteration
// Difficulty: Easy

#include <iostream>
using namespace std;

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 (nullptr == head || nullptr == head->next){
            return head;
        }
        // 取出head然后剩下的链表通过递归去重
        head->next = deleteDuplicates(head->next);
        // 手动去重
        if(head->val == head->next->val){
            ListNode* ret = head->next;
            delete head;
            return ret;
        }else{
            return head;
        }
    }
};

int main()
{
    // system("pause");
    return 0;
}

作者:@臭咸鱼

转载请注明出处:https://www.cnblogs.com/chouxianyu/

欢迎讨论和交流!


原文地址:https://www.cnblogs.com/chouxianyu/p/13288913.html