【LeetCode刷题】83. 删除排序链表中的重复元素

存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次 。

返回同样按升序排列的结果链表。

示例 1:


输入:head = [1,1,2]
输出:[1,2]
示例 2:


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

提示:

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

1 常规解法

/**
 * 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 == NULL)
       {
           return head;
       }
       //临时变量
       ListNode* temp = head;
       while(temp->next != NULL)
       {
           ListNode* p = temp->next;
           if(temp->val == p->val)
           {
               temp->next = p->next;
               delete p;
           }
           else
           {
               temp = temp->next;
           }
       }
       return head;
    }
};

2 递归解法

假设除过第一个的后面是无重复的链表,那么第一个链就只有两种情况:(1)第一个链和第二个链重复、(2)第一个链和第二个链不一样。

如果是(1),直接删掉第一个链;

如果是(2),把链连起来。

/**
 * 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* newNode = deleteDuplicates(head->next);

      if(head->val == newNode->val)
      {
          head->next = NULL;
          return newNode;
      }
      else
      {
          head->next = newNode;
          return head;
      }
    }
};

参考:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/submissions/

猜你喜欢

转载自blog.csdn.net/Zhouzi_heng/article/details/115230686