Remove Duplicates from Sorted Linked List
Problem Statement
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Example
Input
1 -> 1 -> 2 -> 3 -> 3
Output
1 -> 2 -> 3
Approach Iterative Method
Since the list is already sorted, duplicates will be adjacent. We can compare current node with the next node and remove duplicates.
Steps
1 Start from the head node
2 Compare current node with next node
3 If both values are equal, skip the next node
4 Else move to the next node
5 Repeat until end of list
Code
```python id="rdll1"
class ListNode:
def init(self, val=0, next=None):
self.val = val
self.next = next
def deleteDuplicates(head):
current = head
while current and current.next:
if current.val == current.next.val:
current.next = current.next.next
else:
current = current.next
return head
---
## Explanation
Since the list is sorted, all duplicate values are next to each other. We simply skip the duplicate nodes by changing the pointer of the current node.
---
## Expected Output
Input
1 -> 1 -> 2 -> 3 -> 3
Output
1 -> 2 -> 3
---
## Conclusion
This problem helps in understanding linked list traversal and pointer manipulation. It is simple yet important for mastering linked list operations.
Practice this problem to improve your confidence in working with linked lists.
Top comments (0)