0876. Middle of the Linked List #
题目 #
-
给定一个头结点为
head
的非空单链表,返回链表的中间结点。 -
如果有两个中间结点,则返回第二个中间结点。
思路 #
双指针 #
代码 #
双指针 #
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Solution {
public ListNode middleNode(ListNode head) {
ListNode sentinel = new ListNode(-1, head);
ListNode middle = sentinel, fast = sentinel;
while (fast != null && fast.next != null) {
middle = middle.next;
fast = fast.next.next;
}
if (fast != null) middle = middle.next;
return middle;
}
}