876. 链表的中间结点

  • https://leetcode-cn.com/problems/middle-of-the-linked-list/

    问题描述

    image.png

    问题分析

    代码实现

    js

    1. /**
    2. * Definition for singly-linked list.
    3. * function ListNode(val, next) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.next = (next===undefined ? null : next)
    6. * }
    7. */
    8. /**
    9. * @param {ListNode} head
    10. * @return {ListNode}
    11. */
    12. var middleNode = function(head) {
    13. let count = 0
    14. let temp = head
    15. while(temp) {
    16. count++
    17. temp = temp.next
    18. }
    19. for(let i = 0; i < (count-1)/2; i++) {
    20. head = head.next
    21. }
    22. return head
    23. };

    java

    1. class Solution {
    2. public ListNode middleNode(ListNode head) {
    3. if (head.next == null) return head;
    4. if (head.next.next == null) return head.next;
    5. ListNode slow = head.next;
    6. ListNode fast = head.next.next;
    7. while (fast != null && fast.next != null) {
    8. slow = slow.next;
    9. fast = fast.next.next;
    10. if (fast == null) return slow;
    11. }
    12. return slow;
    13. }
    14. }