剑指Offer-17删除链表的节点

public static ListNode deleteNode(ListNode head, int val) {
    //保留头节点
    ListNode p = head;
    // 如果第一个就匹配 直接返回head的下一个节点
    if (p.val == val){
        return head.next;
    }
    // 循环判断
    while (p.next != null){
        if (p.next.val == val){
            // d保留要删除的节点
            ListNode d = p.next;
            // 当前节点指向当前的下下个节点
            p.next = p.next.next;
            // 把要删除的节点next置为空
            d.next = null;
            return head;
        }
        p = p.next;
    }
    return head;
}

猜你喜欢

转载自blog.csdn.net/a792396951/article/details/113631465