Remove Duplicates from Sorted List II, Leetcode 解题笔记

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 node的问题,肯定要用到一个dummy node作为新的头。这道题就是list操作,没有什么难点,只是做list的题时一定要心静,不然很容易把自己搞晕。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode newhead = new ListNode(0);
        newhead.next = head;
        ListNode slow = newhead;
        ListNode fast = head;
        while(slow.next != null){
            while(fast.next != null && fast.next.val == slow.next.val){
                fast = fast.next;
            }
            if(slow.next == fast){
                slow = slow.next;
                fast = fast.next;
            }
            else{
                slow.next = fast.next;
                fast = fast.next;
            }
        }
        return newhead.next;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s