【剑指offer】18. 删除链表的节点

18. 删除链表的节点

难度简单12收藏分享切换为英文关注反馈

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

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

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

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

1.遍历法

th:通过loop遍历 找到等于val的节点 将上一个节点和要删除节点的next节点相连接。

time:O(n)

space:O(1)

public ListNode deleteNode(ListNode head, int val) {
        if(head == null || head.next == null){
            return null;
        }

        //遍历查找到Node.val = val的结点
        ListNode root  = head;

        //如果是头结点就是要删除的节点 直接用root.next 指向根节点  返回即可
        if(root.val == val){
            head = root.next;
            return head;
        }

        while(root.next != null){
            if(root.next.val == val){
                root.next = root.next.next;
                return head;
            }
            root = root.next;
        }

        return head;
    }

2.双指针

th:一共两种情况 1. 头结点就是删除的节点 直接返回head.next 即可。

2.删除的节点在链表中某个位置。 一个pre节点 和 一个 cur节点 cur节点比pre节点快一步 找到删除即可。

time:O(n)

space:O(1)

public ListNode deleteNode(ListNode head, int val) {
        //如果是head节点 直接返回
        if(head.val == val){
            return head.next;
        }

        ListNode pre = head, cur = head.next;
        //遍历寻找
        while(cur != null && cur.val != val){
            pre = cur;
            cur = cur.next;
        }

        if(cur!=null){
            pre.next = cur.next;
        }
        return head;
    }
原文地址:https://www.cnblogs.com/qxlxi/p/12860664.html