DEV Community

Cover image for C# LeetCode 83: Remove Duplicates from Sorted List
Grant Riordan
Grant Riordan

Posted on

C# LeetCode 83: Remove Duplicates from Sorted List

Problem

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.

  • Definition for singly-linked list from LeetCode.
 public class ListNode {
     public int val;
     public ListNode next;
     public ListNode(int val=0, ListNode next=null) {
         this.val = val;
         this.next = next;
     }
 }
Enter fullscreen mode Exit fullscreen mode

Approach

Pretty straight-forward approach

  • Exit early to prevent unnecessary loop creation or single nodes

  • Check if the current value, is the same as the next value (i.e a duplicate), if it is then we skip over the next item by setting the next item, to the one after it with `current.next.next.

Code

`csharp
public ListNode DeleteDuplicates(ListNode head)
{
if (head == null || head.next == null)
return head;

ListNode current = head;

while (current.next != null)
{
    if (current.val == current.next.val)
    {
        // Skip the duplicate node
        current.next = current.next.next;
    }
    else
    {
        current = current.next;
    }
}

return head;
Enter fullscreen mode Exit fullscreen mode

}

`


As always if you want to hear about more articles like this , drop me a follow on DevTo, or twitter/x

Top comments (0)