欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

203. Remove Linked List Elements

程序员文章站 2024-02-19 08:18:46
...

题目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

public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode tempHead = new ListNode(1);
        tempHead.next = head;
        ListNode preNode = tempHead;
        ListNode node = preNode.next;
        while(node != null){
            if(node.val == val){
                preNode.next = node.next;
            }else{
                preNode = node;
            }
            node = preNode.next;
        }
        return tempHead.next;
    }
}