[LeetCode-JAVA] 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

思路:设置前置指针,并随之移动。

代码:

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

 

你可能感兴趣的:(LeetCode)