DEV Community

Cover image for Remove Duplicates from Sorted List
FakeStandard
FakeStandard

Posted on • Edited on

3

Remove Duplicates from Sorted List

#83.Remove Duplicates from Sorted List

Problem statement

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

Input: head = [1,1,2]
Output: [1,2]
Enter fullscreen mode Exit fullscreen mode

Example 2

Input: head = [1,1,2,3,3]
Output: [1,2,3]
Enter fullscreen mode Exit fullscreen mode

Explanation

給定一個從頭開始的已排序鏈結串列,刪除串列裡重複的元素,使每個元素只出現一次,最終返回一個排序好的鏈結串列

Solution

熟悉鏈結串列的話這題不難,刪除重複值的方法是略過下個節點,將節點與下下個節點連接起來,特別注意的地方是要如何知道該節點是重複值,用變數紀錄嗎?還是有其他方法?

我從題目知道該串列是已經排序過,故將當前的節點值與下一個節點值比對是否相同,如果相同就用前面提到的刪除方式,略過下一個節點,將當前節點與下下節點連結起來;若不相同則將指標位置移動到下一個節點,重複以上步驟直到下一個節點指標為 null 為止

public ListNode DeleteDuplicates(ListNode head)
{
    if (head != null)
    {
        var curr = head;

        while (curr != null && curr.next != null)
        {
            if (curr.val == curr.next.val)
                curr.next = curr.next.next;
            else
                curr = curr.next;
        }
    }

    return head;
}
Enter fullscreen mode Exit fullscreen mode

Reference

LeetCode Solution

GitHub Repository


Thanks for reading the article 🌷 🌻 🌼

If you like it, please don't hesitate to click heart button ❤️
or click like on my Leetcode solution
or follow my GitHub ⭐ I'd appreciate it.


Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs