2014年3月19日星期三

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:


 /**  
  * 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)  
     return null;  
     ListNode temp=head;  
     while(temp.next!=null)  
     {  
       if(temp.val==temp.next.val)  
       {  
         if(temp.next.next!=null)  
         temp.next=temp.next.next;  
         else  
         {  
           temp.next=null;  
           break;  
         }  
       }  
       else  
       temp=temp.next;  
     }  
     return head;  
   }  
 }  
Discussion:

Do not forget to consider when head is null. Then the logic is simple. Don't need much to say.

没有评论:

发表评论