leetcode 82 Remove Duplicates from Sorted List II ----- java

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.

去掉链表中出现过的重复的数字,然后返回链表。

就直接遍历一次就好了,做好标记。

/**
 * 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 result = head;
        ListNode first = head;
        ListNode flag ;
        int DD = 0;
        if( head.val == head.next.val )
            DD = 1;
        int del = 0;
        while( first.next != null){
            flag = first.next;
            if( first.val == flag.val){
                del = 1;
            }else{
                if( del == 0 && !head.equals(first) ){
                    result.next = first;
                    result = result.next;
                }
                del = 0;
            }
            first = first.next;
        }
        if( del == 0){
            result.next = first;
            result = result.next;
        }
        result.next = null;
        if( DD == 1 )
            return head.next;
        else
            return head;

    }
}
原文地址:https://www.cnblogs.com/xiaoba1203/p/5974387.html