题目描述

题解
/**
* 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
cur = cur.next
}
return cur
}
}
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;
}
}