Delete duplicate elements in the linked list Ⅱ

1. Demand

  • Given a sorted linked list, delete all nodes with repeated numbers, and only keep the numbers that do not appear repeatedly in  the original linked list  .

Example 1:

Input: 1->2->3->3->4->4->5
 Output: 1->2->5

Example 2:

Input: 1->1->1->2->3
 Output: 2->3

Second, the recursive method

2.1 Thinking analysis

  1. There are two tasks to be completed by the recursive method: ①For repeated elements, it should be skipped directly; ②For non-repetitive elements, establish connections;
  2. It is worth noting that why can this problem be solved by recursion? First look at the function of this method is to return an ascending linked list with no duplicate elements, that is to say we can locate the first non-duplicated element in the original linked list, and its next can be implemented by this method, and so on, the original problem can be solved Decompose into multiple sub-problems;

2.2 Code implementation

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }
        ListNode nextNode = head.next;
        if(nextNode.val == head.val) {
            //定位到链表的不重复节点
            while(nextNode != null && nextNode.val == head.val) {
                nextNode = nextNode.next;
            }
            //舍弃重复节点部分
            head = deleteDuplicates(nextNode);  
        } else {
            //连接无重复的节点
            head.next = deleteDuplicates(head.next);
        }
        return head;
    }
}

2.3 Complexity analysis

  • The time complexity is O(N), and all linked list nodes need to be traversed;
  • The space complexity is O(N), and the recursion depth can reach up to N;

Guess you like

Origin blog.csdn.net/Sruggle/article/details/113834557