203. Remove Linked List Elements

 
 
/**
 * 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) {
      ListNode dummy = new ListNode(-1);
      dummy.next = head;
      ListNode prev = dummy;
      ListNode cur = head;
      
      while( cur != null){
        if(cur.val == val){
          prev.next = cur.next;
        }else{
          prev = cur;
        }
        cur = cur.next;
      }
      return dummy.next;
        
    }
}

 

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

posted on 2018-07-18 09:13  猪猪🐷  阅读(63)  评论(0)    收藏  举报

导航