Monday, January 5, 2015

Remove Duplicates from Sorted List (LeetCode Linked List)

Question: 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.

Idea: Use a pointer "pre" to traverse the whole list. Whenever pre.next.val==pre.val, skip the next node by pre.next=pre.next.next; otherwise push pre forward one step pre=pre.next.

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   public ListNode deleteDuplicates(ListNode head) {  
     if(head==null||head.next==null)  
       return head;  
     ListNode pre=head;  
     while(pre.next!=null)  
     {  
       if(pre.next.val==pre.val)  
         pre.next=pre.next.next;  
       else  
         pre=pre.next;  
     }  
     return head;  
   }  
 }  

No comments:

Post a Comment