Remove-duplicates-from-sorted-list

HowieLee59發表於2018-07-25

題目描述

 

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given1->1->2, return1->2.
Given1->1->2->3->3, return1->2->3.

 

/**
 * 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) {
        //ListNode tail = head;
        while(head != null){
            while(head.next != null && head.val == head.next.val){
                head.next = head.next.next;
            }
            head = head.next;
        }
        return head;
    }
}