82. Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,

Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

一刷
题解:
这里要建立一个fake head,因为假如全部为重复(head和head.next比较),需要移除所有的元素。 还需要一个count变量来判断当前状态是否重复。最后判断循环结束时的边界状态。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode node = dummy;
        int count = 1;
        while(head!=null && head.next!=null){
            if(head.val != head.next.val){
                if(count == 1){//append to the node, node denote to a tail
                    node.next = head;
                    node = node.next;
                }
                count = 1;
            }
            else{
                count++;
            }
            head = head.next;
        }
        node.next = (count==1)? head:null;
        return dummy.next;
    }
}

二刷:
用cur遍历链表。cur.next是预备存入的node

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
       if(head == null) return head;
       ListNode dummy = new ListNode(-1);
        ListNode prev = dummy;
        prev.next = head;
        ListNode cur = head;
        while(cur!=null){
            while(cur.next!=null && cur.val == cur.next.val){
                cur = cur.next;
            }
            
            if(prev.next == cur){
                prev = prev.next;
            }
            else{
                prev.next = cur.next;
            }
            cur = cur.next;
        }
        return dummy.next;
        
    }
}

你可能感兴趣的:(82. Remove Duplicates from Sorted List II)