Remove Linked List Elements

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

Example:

Input: 1->2->6->3->4->5->6, val = 6 
Output: 1->2->3->4->5

Analysis

需要记录prev指针方便找到val时移除当前节点

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

results matching ""

    No results matching ""