leetcode-82. Remove Duplicates from Sorted List II

leetcode-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.

基本思路:由于需要删除所有的重复节点所以需要维护三个坐标。两个坐标分别是重复数值的左右两端点,1个指针pre指向左端点的坐边第一个节点。

首先新建一个哑节点,然后让pre指向哑节点,然后新建左右节点分别指向head和head.next,然后同时移动着三个节点。如果发现l节点和r节点相同则移动r节点直到r和r.next不相同为止,说明l和r分别指向了重复值得的左右节点。然后做替换就好。当然还需要考虑null节点情况。

/**
 * 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 dump = new ListNode(0);
        dump.next = head;
        ListNode n = head.next;
        ListNode pre = dump;
        while(n!=null){
            if(head.val == n.val){
                while(n.next!=null && n.next.val == n.val) n=n.next;
                pre.next = n.next;
                head = pre.next;
                if(head==null || head.next==null) break;
                n = head.next;
            }else{
                pre = pre.next;
                head = head.next;
                n = n.next;
            }
        }
        return dump.next;
    }
}

你可能感兴趣的:(JAVA,leetcode,leetcode,java)