Saturday, September 9, 2017

203. Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

Solution:
1.Use preDummy trick
2. Use pre iterator to check pre.next.val if it is the value we want to remove, remove pre.next, if not iterate to next pointer.

 public ListNode removeElements(ListNode head, int val) {  
    ListNode preDummy=new ListNode(0);  
     preDummy.next=head;  
     ListNode pre=preDummy;  
     while(pre.next!=null){  
       ListNode temp=pre.next;  
       if(temp.val==val){  
         pre.next=temp.next;  
         temp.next=null;          
       }  
       else pre=pre.next;  
     }  
     return preDummy.next;  
   }  

No comments:

Post a Comment