题目描述
思路:快慢指针
- 快指针一次走两步
- 慢指针一次走一步
- 当快指针到达末尾的时候,慢指针所指的就是链表的中点
方法一:
/**
* Definition for singly-linked list.
* 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 fast = head, slow = head;
while (fast != null && fast.next != null) {
// 快指针一次走两步, 慢指针一次走一步
fast = fast.next.next;
slow = slow.next;
}
// 慢指针最终指向的位置就是链表的中点
return slow;
}
}
标签:结点,ListNode,val,fast,next,链表,LeetCode876,指针
From: https://www.cnblogs.com/keyongkang/p/17883810.html