Remove Duplicates From Sorted List Ii
To solve this coding challenge, we need to remove all nodes from a sorted linked list that have duplicate numbers, leaving only distinct numbers, and return the sorted linked list. Below, I explain the methodology and provide a detailed step-by-step pseudocode to achieve the solution.
Explanation
We start by examining the properties of the linked list given:- The linked list is sorted in ascending order.
- We will delete nodes that have duplicates, ensuring that only unique values remain. Our approach involves the following:
- Dummy Node : We use a dummy node to handle edge cases, such as removing the first node of the list. The dummy node points to the head of the list.
-
Two Pointers
: We use two pointers,
prev
head
- Identify Duplicates : As we traverse the list, we check if the current node's value is equal to the next node's value. If it is, there are duplicates. We then skip over all nodes with this duplicate value.
-
Update Links
: Once duplicates are bypassed, we link the
prev
-
Return Result
: At the end of the traversal, the list starting from
dummy.next
- Initialize Dummy Node : Create a dummy node that points to the head of the list.
-
Set up Pointers
: Initialize
prev
head
- Traverse the List :
-
While
head
-
Check if
head.next
head.val
head.next.val
- If true, it means duplicates exist:
-
Skip all nodes with this duplicate value by advancing
head
-
Link
prev.next
prev.next
head.next
-
If false, advance the
prev
head
-
Move
head
-
Return the Result
: Return
dummy.next
Step-by-Step Explanation / Detailed Steps in Pseudocode
# Class definition for ListNode, used for creating new list nodes
Class ListNode:
Function __init__(val, next=null):
self.val = val
self.next = next
Function deleteDuplicates(head):
# If the list is empty or has single node, return head directly as no duplicates exist
If head is null OR head.next is null:
Return head
# Create a dummy node pointing to the head of the list
dummy = new ListNode(0)
dummy.next = head
# Initialize the βprevβ pointer to dummy and βheadβ pointer to the head of the list
prev = dummy
# Traverse the entire list
While head is not null:
# If the current node and the next node have the same value, it indicates duplicates
If head.next is not null AND head.val == head.next.val:
# Skip all nodes with this duplicate value
While head.next is not null AND head.val == head.next.val:
head = head.next
# Connect 'prev.next' to the node after the duplicates
prev.next = head.next
Else:
# If no duplicates, advance 'prev' to next node
prev = prev.next
# Move βheadβ to the next node in the list
head = head.next
# Return the new head of the list which is dummy.next
Return dummy.next
This pseudocode clearly outlines each step and incorporates comments for better understanding of each action being performed. It adheres to the method of solving the coding challenge, ensuring no unnecessary language-specific constructs are used.