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

Middle Of The Linked List Problem

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

Linked List Components Problem

LeetCode 817. You are given the head of a linked...

Split Linked List In Parts Problem

LeetCode 725. Given the head of a singly linked list...

All O'One Data Structure Problem

LeetCode 432. Design a data structure to store the strings...

Add Two Numbers II Problem

LeetCode 445. You are given two non-empty linked lists representing...