動態

詳情 返回 返回

[leetcode]876. 鏈表的中間結點 - 動態 詳情

示例
輸入:head = [1,2,3,4,5]
輸出:[3,4,5]
解釋:鏈表只有一箇中間結點,值為 3 。

輸入:head = [1,2,3,4,5,6]
輸出:[4,5,6]
解釋:該鏈表有兩個中間結點,值分別為 3 和 4 ,返回第二個結點。

思路

數組

  1. 鏈表轉存數組,有順序下標,根據長度判斷中間點。
  2. 遍歷鏈表
  3. 新建數組
  4. 鏈表填充到數組中
  5. 返回數組長度中間
func middleNode(head *ListNode) *ListNode {
    var tmp []*ListNode
    for head != nil {
        tmp = append(tmp, head)
        head = head.Next
    }

    return tmp[len(tmp)/2]
}

快慢指針

  1. 快指針->2步,慢指針->1步。
  2. 快指針移動到末端,慢指針移動到中間點。
func middleNode(head *ListNode) *ListNode {
  slow, fast := head, head
  for fast != nil && fast.Next != nil {
      fast = fast.Next.Next
      slow = slow.Next
  }
    return slow
}
user avatar hoistthecolorsandsteptotherail 頭像 iicode 頭像 houbinbin 頭像 jidcoo 頭像 seven97_top 頭像
點贊 5 用戶, 點贊了這篇動態!
點贊

Add a new 評論

Some HTML is okay.