[LeetCode Brush Questions] 83. Delete duplicate elements in the sorted list

There is a linked list arranged in ascending order. Give you the head node of this linked list. Please delete all the repeated elements so that each element only appears once.

Return a linked list of results also sorted in ascending order.

Example 1:


Input: head = [1,1,2]
Output: [1,2]
Example 2:


Input: head = [1,1,2,3,3]
Output: [1,2,3]

prompt:

The number of nodes in the linked list is within the range [0, 300]
-100 <= Node.val <= 100 The
question data ensures that the linked list has been arranged in ascending order

1 Conventional solution

/**
 * 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 Recursive solution

Assuming that there is a non-repetitive linked list after the first one, there are only two cases for the first chain: (1) the first chain and the second chain are repeated, (2) the first chain and the second chain The chain is not the same.

If it is (1), delete the first chain directly;

If it is (2), connect the chains.

/**
 * 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;
      }
    }
};

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

Guess you like

Origin blog.csdn.net/Zhouzi_heng/article/details/115230686