Loading

LeetCode problem#83

Remove Duplicates from Sorted List

Solved in 1 languageJava

Solve it on LeetCode(opens in a new tab)

Solution

29 lines
1/**
2 * Definition for singly-linked list.
3 * public class ListNode {
4 *     int val;
5 *     ListNode next;
6 *     ListNode() {}
7 *     ListNode(int val) { this.val = val; }
8 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9 * }
10 */
11class Solution {
12    public ListNode deleteDuplicates(ListNode head) {
13        ListNode curr = head;
14
15        while (curr != null) {
16            if (curr.next != null && curr.next.val == curr.val) {
17                ListNode next = curr.next;
18                curr.next = curr.next.next;
19                // Deallocate memory for duplicate node (might be garbage collected)
20                next.next = null;
21            }
22            else {
23                curr = curr.next;
24            }
25        }
26
27        return head;
28    }
29}

Want a walkthrough of this Java solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.