Leetcode203.移除链表元素

发布时间 2023-10-16 20:24:11作者: 白布格

题目描述

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点。

示例

image

提交的代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        //设置虚头部
        ListNode fakeHead=new ListNode(-1,head);
        //使得next指向下一节点
        ListNode nextNode=head;
        //当前节点的Node
        ListNode current=head;
        //前节点
        ListNode pre=fakeHead;
        //遍历链表
        while(nextNode!=null){
            //next指针向后运动
            nextNode=nextNode.next;
            if(current.val==val){
                pre.next=nextNode;
            }else{
                pre=current;
            }
            current=nextNode;
        }

        return fakeHead.next;
    }
}

增加一个虚头来使得增删的代码逻辑统一