(Easy) Removed Linked List Element (LeetCode)

Description:

Remove all elements from a linked list of integers that have value val.

Example:

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
Accepted
244,837
Submissions
674,366
 

Solution:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        
        if(head ==null){
            return head;
        }
        

        ListNode lst = head; 
     
       while(lst.next!=null){
            
          if(lst.next.val ==val){
              lst.next = lst.next.next;
          }
           else{
           
                lst= lst.next;
          }
          
       }
        
          
            return head.val==val? head.next: head;
    }
        
}

 

posted @ 2019-08-28 17:27  CodingYM  阅读(77)  评论(0编辑  收藏  举报