5/30/2014

12. Remove Duplicates From Sorted 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 dummy = new ListNode(0);
        dummy.next = head;
       
        while (head.next!=null) {
            if (head.val!=head.next.val) head = head.next;
            else head.next = head.next.next;
        }
       
        return dummy.next;
    }
}

1 条评论: