Leetcode 82) Remove Duplicates from Sorted List II

image

My Answer

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head==null)return head;
        ListNode prev= new ListNode();
        prev.next= head;
        ListNode res = prev;
        ListNode dummy= head;

        while(dummy!=null && dummy.next!=null){
            boolean repeat=false;
            while(dummy.next!=null && dummy.val==dummy.next.val){
                dummy.next=dummy.next.next;
                repeat=true;
            }
            if(repeat){
                prev.next=dummy.next;
                dummy=prev.next;
            }else{
                prev=prev.next;
                dummy=dummy.next;
            }
        }

        return res.next;
    }
}

Other Answer

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode sentinel = new ListNode(0, head);    

        ListNode prev = sentinel;

        while (head != null) {
            if (head.next != null && head.val == head.next.val) {
                while (head.next != null && head.val == head.next.val) {
                    head = head.next;
                }
                prev.next = head.next;
            } else {
                prev = prev.next;
            }
            head = head.next;
        }
        return sentinel.next;
    }
}

© 2018. All rights reserved.

Powered by Hydejack v8.5.2