My staightforward java solution


  • 0
    H

    This is the solution that creates a brand new linklist:

       public class Solution {
            public ListNode deleteDuplicates(ListNode head) {
                if(head == null || head.next == null) return head;
                ListNode newNode = new ListNode(head.val);
                ListNode start = newNode, current = head.next;
                while(current != null){
                    if(current.val != start.val){
                        ListNode node = new ListNode(current.val);
                        start.next = node;
                        start = node;
                    }
                    current = current.next;
                }
                return newNode;
            }
        }
    

    Here is the solution which uses the old linklist, but generally takes more time than the first solution. I guess this is an exact example of the compromise between time and space :)

    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            if(head == null || head.next == null) return head;
            ListNode first = head, second = head.next;
            while(second != null){
                if(second.val != first.val){
                    first.next = second;
                    first = second;
                }
                else first.next = null;
                second = second.next;
            }
            return head;
        }
    }

Log in to reply
 

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