The challenge
Remove repeated values from a sorted list, keeping the first node of each value.
Sorted nondecreasing input. This keeps one copy; it does not remove every value that appeared more than once.
Example
[1, 1, 2, 3, 3] → [1, 2, 3].
Use the walkthrough below to inspect the input and each state change.
See Remove duplicates, step by step
Follow the pointers. Watch each link change.
A1Inspect node links
| Node | Value | Next |
|---|---|---|
| A1 | 1 | A2 |
| A2 | 1 | A3 |
| A3 | 2 | A4 |
| A4 | 3 | A5 |
| A5 | 3 | null |
Read the input
IDs label node objects. Equal values can belong to different nodes. Solid arrows are next links; dashed arrows are random links.
Start from the input head pointers.View original input
A: 1 (A1) → 1 (A2) → 2 (A3) → 3 (A4) → 3 (A5); parameters: {}
Parameter indices are zero-based, except n from the end, which is one-based. Node IDs remain fixed when links change.
Put it into code
Sorted order puts every duplicate beside the node that should survive.
Node stores val and next; the random-pointer lesson adds random. C++ uses C++17 or later.
class Node:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def deduplicate(head):
curr = head
while curr and curr.next:
if curr.val == curr.next.val:
curr.next = curr.next.next
else:
curr = curr.next
return head
#include <cstddef>
struct Node {
int val;
Node* next;
Node(int value = 0, Node* link = nullptr)
: val(value), next(link) {}
};
Node* deduplicate(Node* head) {
Node* curr = head;
while (curr && curr->next) {
if (curr->val == curr->next->val) {
Node* removed = curr->next;
curr->next = removed->next;
delete removed;
} else {
curr = curr->next;
}
}
return head;
}