Friday, August 1, 2014

[LeetCode] Remove Duplicates from LinkedList

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.
 
解题思路:
  用2个指针,将重复的给删除掉

Java Code:

public ListNode deleteDuplicates(ListNode head) {
         if(head == null) return head;
        
         ListNode prev = head;
         ListNode p = prev.next;
         
        while(p != null){
            if(p.val != prev.val){
                prev = p;
                p = p.next;
            }else{
                p = p.next;
                prev.next = p;
            }
        }
        
        return head;
    }

No comments:

Post a Comment