美文网首页
剑指 Offer 18. 删除链表的节点

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

作者: Abeants | 来源:发表于2021-11-25 21:55 被阅读0次

给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。

返回删除后的链表的头节点。

注意:此题对比原题有改动

示例 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.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路及方法

老生常谈了哈。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteNode(ListNode head, int val) {
        if (head == null) return null;
        if (head.val == val) return head.next;

        ListNode pre = head;
        ListNode next = head.next;
        while (next.val != val) {
            pre = next;
            next = next.next;
        }

        // 连接删除后的链表
        pre.next = next.next;

        return head;
    }
}

结果如下:

相关文章

网友评论

      本文标题:剑指 Offer 18. 删除链表的节点

      本文链接:https://www.haomeiwen.com/subject/dqiztrtx.html