MrainW's Home

All things come to those who wait!

0%

LeetCode 82. Remove Duplicates from Sorted List II

Question

Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.

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

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy, cur = head;
while(cur != null && cur.next != null){
if(cur.val == cur.next.val){
int temp = cur.val;
while(cur != null && temp == cur.val) cur = cur.next;
pre.next = cur;
} else {
pre = pre.next;
cur = cur.next;
}
}
return dummy.next;
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(1)

Welcome to my other publishing channels