尼采般地抒情

尼采般地抒情

尼采般地抒情

音乐盒

站点信息

文章总数目: 315
已运行时间: 1554


876. 链表的中间结点

问题描述

问题分析

代码实现

js

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var middleNode = function(head) {
    let count = 0
    let temp = head
    while(temp) {
        count++
        temp = temp.next
    }
    for(let i = 0; i < (count-1)/2; i++) {
        head = head.next
    }
    return head
};

java

class Solution {
    public ListNode middleNode(ListNode head) {
        if (head.next == null) return head;
        if (head.next.next == null) return head.next;

    ListNode slow = head.next;
    ListNode fast = head.next.next;
    while (fast != null &amp;&amp; fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
        if (fast == null) return slow;
    }
    return slow;
}

}


评论区