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.

该题意思是删除链表中的重复数字,由于链表的head也可能被删除,因此需要加一个dummy node,可以使代码更加简洁

public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null)
            return head;
        //建一个dummy node,指向链表头部
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;
       //当链表结点的next和next.next均不为空时循环,因为需要比较这两个结点的val是否相等
        while (head.next != null && head.next.next != null) {
            if (head.next.val == head.next.next.val) {
               //记录下重复的值     
                int val = head.next.val;
               //遍历删除所有值重复的结点
                while (head.next != null && head.next.val == val) {
                    head.next = head.next.next;
                }            
            } else {
                head = head.next;
            }
        }
        return dummy.next;
    }
}

 

posted @ 2017-03-27 22:26  bubbleStar  阅读(83)  评论(0编辑  收藏  举报