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

public class Test {
    public ListNode removeElements(ListNode head,int val){
        if (head==null){
            return head;
        }
        ListNode prev=head;
        ListNode cur=head.next;
        while (cur != null){
            if (cur.val==val){
                prev.next=cur.next;
                cur=cur.next;
            }
            prev=cur;
            cur=cur.next;
        }
        if (head.val==val){
            head=head.next;
        }
        return  head;
    }
}

 

输入:head=[1,2,6,3,2,6], val=6

输出:[1,2,3,2]

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐