【Leetcode】876. 链表的中间结点

131 阅读1分钟

题目描述

在这里插入图片描述

// 876. 链表的中间结点

// 给定一个头结点为 head 的非空单链表,返回链表的中间结点。
// 如果有两个中间结点,则返回第二个中间结点。

题解

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

// 数链表长度
// 先让指针cur走一遍链表,将链表的长度记录出来。
// 走完之后,cur回到head,让cur指针走长度的一半,就来到了链表的中点。

// 执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
// 内存消耗:35.7 MB, 在所有 Java 提交中击败了59.18%的用户
class Solution {
    public ListNode middleNode(ListNode head) {
        if (head == null)
            return null;
		int length = 0;
		ListNode cur = head;
        while (cur != null) {
            cur = cur.next;
            length++;
        }
        cur = head;
        for (int i = 0; i < length/2; i++) {
            cur = cur.next;
        }
        return cur;
    }
}

// 快慢针
// 如果一个指针pre走1步,一个指针cur走2步,那么当cur到达链表尾时,
// pre正好就到达链表的中点。

// 执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
// 内存消耗:35.9 MB, 在所有 Java 提交中击败了29.65%的用户
class Solution {
    public ListNode middleNode(ListNode head) {
        if (head == null)
            return null;
		ListNode cur = head;
        ListNode pre = head;
        while (cur != null && cur.next != null) {
            cur = cur.next.next;
            pre = pre.next;
        }
        return pre;
    }
}