C# solution with comment explanation (one loop)


  • 0
    K
    public class Solution {
        public ListNode DeleteDuplicates(ListNode head) {
            
            if (head == null || head.next == null) return head;
            //we add a dummy node to the beginning of the list
            int min = Int32.MinValue;
            ListNode node = new ListNode(min);
            node.next = head;
            //we use three pointers
            ListNode distinct = node; //distinct node
            ListNode prev = node; //previous node
            ListNode cur = head; //current node
            //we compare each current node with the previous node and the next node, 
            //if it is different from both of them then it is a distinct node
            while (cur!=null) {
                if (((prev.val == min && cur == head) || cur.val != prev.val) && (cur.next == null || (cur.val != cur.next.val))) {
                    distinct.next = cur;
                    distinct = cur;
                }
                prev = prev.next;
                cur = cur.next;
            }
            distinct.next = cur;
            return node.next;
        }
    }
    

Log in to reply
 

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