C# beats 96%


  • 0
    M

    My solution simply iterates through the list and checks if a node is equal to it's predecessor or successor. If it is not a duplicate it copies the node to a result list that contains the non-duplicates.

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode DeleteDuplicates(ListNode head) 
        {        
            // handle empty case
            if (head == null)
            {
                return head;
            }
            
            // handle single node case
            if (head.next == null)
            {
                return head;
            }
            
            ListNode retListHead = null;
            ListNode retListCur = null;
            ListNode prev = null;
            
            for (ListNode curNode = head; curNode != null; prev = curNode, curNode = curNode.next)
            {
                if (!((prev != null && curNode.val == prev.val) ||
                   (curNode.next != null && curNode.val == curNode.next.val)))
                {
                    if (retListCur == null)
                    {
                        retListHead = new ListNode(curNode.val);
                        retListCur = retListHead;
                    }
                    else
                    {
                        retListCur.next = new ListNode(curNode.val);
                        retListCur = retListCur.next;
                    }
                }
            }
            
            return retListHead;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.