Remove Duplicates from Sorted List Problem


Description

LeetCode Problem 83.

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 1:

1
2
Input: head = [1,1,2]
Output: [1,2]

Example 2:

1
2
Input: head = [1,1,2,3,3]
Output: [1,2,3]

Constraints:

  • The number of nodes in the list is in the range [0, 300].
  • -100 <= Node.val <= 100
  • The list is guaranteed to be sorted in ascending order.


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* currNode;
        ListNode* prevNode;
        
        if ((head == NULL) || (head->next == NULL))
            return head;
        prevNode = head;
        currNode = head->next;
        
        while (currNode != NULL) {
            if (prevNode->val == currNode->val) {
                currNode = currNode->next;
                prevNode->next = currNode;
            } else {
                currNode = currNode->next;
                prevNode = prevNode->next;
            }
        }
        
        return head;
    }
};




Related Posts

Flatten Binary Tree To Linked List Problem

LeetCode 114. Given the root of a binary tree, flatten...

Remove Duplicates from Sorted List Problem

LeetCode 83. Given the head of a sorted linked list,...

Rotate List Problem

LeetCode 61. Given the head of a linked list, rotate...

Reverse Nodes in k-Group Problem

LeetCode 25. Given a linked list, reverse the nodes of...

Swap Nodes in Pairs Problem

LeetCode 24. Given a linked list, swap every two adjacent...