Middle of the Linked List

題目
Given a non-empty, singly linked list with head node head, return a middle node of linked list.

If there are two middle nodes, return the second middle node.

Example 1:

Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
Example 2:

Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.

答案

class Solution {
    public ListNode middleNode(ListNode head) {
        if(head == null) return null;
        ListNode fast = head, slow = head;
        while(slow.next != null) {
            if(slow.next.next == null) return fast.next;
            slow = slow.next.next;
            fast = fast.next;
        }
        return fast;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,840評(píng)論 0 10
  • 流動(dòng)的露水,腐蝕著鼻根。來自天際的長(zhǎng)風(fēng),呼嘯著穿過我的窗戶。天陰陰暗暗,差一點(diǎn)電閃雷鳴,就可以還原曾經(jīng)的悸動(dòng)。人生...
    木陽灑雪閱讀 247評(píng)論 0 1
  • 等著你 翠滴輕落入泥 宛若你腳步輕移 佇立窗臺(tái)不肯離去 遠(yuǎn)望黑云漸漸散去 等七彩祥云飄來 我踏上北去 見你抱你 不...
    定格不留白閱讀 224評(píng)論 0 0
  • 一本書、一杯茶、一首歌,一抹陽光落在臉龐,這就是我最愜意的周末時(shí)光! 讀書,就像人和人之間的愛情...
    張小勇寫字的地方閱讀 251評(píng)論 0 3

友情鏈接更多精彩內(nèi)容