当前位置 : 主页 > 手机开发 > ROM >

82. Remove Duplicates from Sorted List II

来源:互联网 收集:自由互联 发布时间:2021-06-10
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Example 1: Input: 1-2-3-3-4-4-5Output: 1-2-5 Example 2: Input: 1-1-1-2-3Output: 2-3 /** * Definition for singly-

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

Example 1:

Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:

Input: 1->1->1->2->3
Output: 2->3
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null) return null;
        ListNode dummy = new ListNode(0);
        ListNode prev = dummy;
        prev.next = head;
        ListNode cur = head;
        while(cur!=null && cur.next != null){//缺一不可
            boolean dup = false;
            while(cur.next!=null &&cur.val == cur.next.val){//缺一不可
                cur = cur.next;
                dup = true;
            }
            if(dup){
                prev.next = cur.next;
            }
            else{
                prev = cur;
            }
            cur = cur.next;
        }
        return dummy.next;
    }
}

分享图片

网友评论