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

Intersection Of Two Linked Lists Problem

LeetCode 160. Given the heads of two singly linked-lists headA...

Sort List Problem

LeetCode 148. Given the head of a linked list, return...

Reorder List Problem

LeetCode 143. You are given the head of a singly...

Linked List Cycle Problem

LeetCode 141. Given head, the head of a linked list,...

Linked List Cycle II Problem

LeetCode 142. Given the head of a linked list, return...

Insertion Sort List Problem

LeetCode 147. Given the head of a singly linked list,...