Simple Solution in C#


  • 0
    P
    public class Solution {
        public ListNode DeleteDuplicates(ListNode head) {
            if (head == null || head.next == null)
                    return head;
    
                ListNode current = head;
                ListNode matchwith = current.next;
    
                ListNode nextHead = new ListNode(-1);
    
                if (current.val != matchwith.val)
                    nextHead.next = new ListNode(current.val);
    
                while (matchwith != null)
                {
                    if ((current.val != matchwith.val) && (matchwith.next == null || matchwith.val != matchwith.next.val))
                    {
                        // add it into new list
                        ListNode add = nextHead;
                        while (add.next != null)
                        {
                            add = add.next;
                        }
                        add.next = new ListNode(matchwith.val);
                    }
    
                    current = matchwith;
                    matchwith = current.next;
                }
    
                return nextHead.next;
        }
    }
    

Log in to reply
 

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