2014年4月20日 星期日

[LeetCode] Remove Duplicates from Sorted List

Problem:
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
Solution:O(n)
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
       if(head == null)
          return null;

       int pre = head.val;
       ListNode next = head.next;
       ListNode cur = head;

       while(next!=null){
           if(pre != next.val){
               pre = next.val;
               cur.next = next;
               cur = next;
           }
           next = next.next; 
       }

       cur.next = null;
       return head;
    }
}

沒有留言:

張貼留言