leetcode5943. 删除链表的中间节点(mid)(周赛)


力扣链接

题目描述

给你一个链表的头节点 head删除 链表的 中间节点 ,并返回修改后的链表的头节点 head

长度为 n 链表的中间节点是从头数起第 ⌊n / 2⌋ 个节点(下标从 0 开始),其中 ⌊x⌋ 表示小于或等于 x 的最大整数。

  • 对于 n = 12345 的情况,中间节点的下标分别是 01122

解题思路

  • 两次遍历
  • 快慢指针

代码(两次遍历

class Solution {
    
    
    public ListNode deleteMiddle(ListNode head) {
    
    

        ListNode tou = new ListNode(0, head);
        ListNode temp = head;
        int count = 0;
        //得到节点个数
        while (temp != null) {
    
    
            count++;
            temp = temp.next;
        }
        int avg = count / 2;
        temp = tou;
        for (int i = 0; i < avg; i++) {
    
    
            temp = temp.next;
        }
        //删除节点
        temp.next = temp.next.next;
        return tou.next;
    }
}

复杂度

  • 时间复杂度: O(n)
  • 空间复杂度: O(1)

代码(快慢指针)

class Solution {
    
    
    public ListNode deleteMiddle(ListNode head) {
    
    

        ListNode tou = new ListNode(0, head);
        ListNode first = head;
        ListNode second = tou;
        while (first != null && first.next != null) {
    
    
            first = first.next.next;
            second = second.next;
        }
        //删除节点
        second.next = second.next.next;
        return tou.next;
    }
}

复杂度

  • 时间复杂度: O(n)
  • 空间复杂度: O(1)

猜你喜欢

转载自blog.csdn.net/qq_43478625/article/details/121728739