剑指 Offer 18. 删除链表的节点

问题描述
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。

示例 1:
输入: head = [4,5,1,9], val = 5
输出: [4,1,9]
解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.

示例 2:
输入: head = [4,5,1,9], val = 1
输出: [4,5,9]
解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.

问题解决
考察队链表的操作

class Solution {
    public ListNode deleteNode(ListNode head, int val) {
        if(head == null) return head;
        ListNode pre = new ListNode(0);
        ListNode res = pre;
        pre.next = head;
        while(head != null) {
            if(head.val == val) {
                pre.next = head.next;
                head = head.next;
                break;
            }
            pre = head;
            head = head.next;
        }
        return res.next;
    }
}

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof


版权声明:本文为JhonyLin原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。