203. 移除链表元素

81 阅读1分钟

题目描述:

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

image.png

题解思路:

1、删除指定的元素,有可能删除头节点,所以会存在换头的情况,所以要临时准备一个新的头节点记作:newNode

2、准备临时变量 cur 用来记录当前节点的位置,准备变量 next 用来记录下一个节点的位置。

3、cur步为空就循环,将节点指不等于val的依次放入到newNode中 , 最后返回newNode的下一个节点即可


public static ListNode removeElements(ListNode head, int val) {
    if (head == null){
        return null;
    }
    ListNode newNode = new ListNode();
    ListNode temp = newNode;

    ListNode cur = head;
    ListNode next = null;

    while(cur!=null){
        next = cur.next;
        cur.next = null;
        if (cur.val!=val){
            newNode.next = cur;
            newNode = newNode.next;
        }
        cur = next;
    }
    return temp.next;
}