/**
* 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;
ListNode slow = head;
while (true) {
if (fast.next == null) { // 奇数情况
return slow;
}
if (fast.next.next == null) { // 偶数情况
return slow.next;
}
fast = fast.next.next;
slow = slow.next;
}
}
}
876 链表的中间结点
最新推荐文章于 2024-11-12 15:39:48 发布