Go 語言程式:單次迭代獲取連結串列中間元素


在 Go 語言資料結構中,連結串列使用指標連線各個元素,從第一個節點(頭部)到最後一個節點(尾部),可以透過 next 指標訪問每個節點。我們將使用兩種方法獲取連結串列的中間元素。第一種方法使用雙指標法,第二種方法使用計數器變數來執行程式。

方法 1:使用雙指標法

在這種方法中,函式使用兩個指標 low 和 high 遍歷連結串列。high 指標每次移動兩步,而 low 指標每次移動一步。當 high 指標到達連結串列末尾時,low 指標將指向連結串列的中間元素。

演算法

  • 步驟 1 − 建立一個名為 main 的包,並在程式中宣告 fmt(格式化包),其中 main 生成可執行程式碼,fmt 幫助格式化輸入和輸出。

  • 步驟 2 − 建立一個節點結構體,其中包含型別為 int 的值和型別為 node 的 next 指標。

  • 步驟 3 − 建立一個名為 middle_node 的函式,並在該函式中進一步建立兩個指標 low 和 high,並將它們都設定為指向連結串列的頭部。

  • 步驟 4 − 迴圈遍歷連結串列,直到 high 指標到達連結串列末尾。

  • 步驟 5 − 在每次迴圈中,將 low 指標移動一步,high 指標移動兩步。

  • 步驟 6 − 當 high 指標到達連結串列末尾時,low 指標將指向連結串列的中間元素。

  • 步驟 7 − 在下一步中,將 low 指標返回到函式。

  • 步驟 8 − 對於具有奇數個元素的連結串列,當 high 指標到達連結串列末尾時,low 指標將指向中間元素。對於具有偶數個元素的連結串列,low 指標將指向兩個中間元素中的一個。

示例

在本例中,我們使用了雙指標法從連結串列中獲取中間元素。

package main
import "fmt"

type Node struct {
   value int
   next  *Node
}

func middle_node(head *Node) *Node {
   low, high := head, head
   for high != nil && high.next != nil {
      low = low.next
      high = high.next.next
   }
   return low  //the low is pointing to middle element
}

func main() {
   head := &Node{value: 10}  //store values in the linked list
   head.next = &Node{value: 20}
   head.next.next = &Node{value: 30}
   head.next.next.next = &Node{value: 40}
   head.next.next.next.next = &Node{value: 50}
   
   node := middle_node(head)   //obtain the middle node from the linked list
   fmt.Println("The middle node in the linked list is:", node.value)
}

輸出

The middle node in the linked list is: 30

方法 2:使用計數器變數

在這種方法中,我們首先計算連結串列中元素的數量。然後再次遍歷連結串列,透過迭代 count/2 次來停止在中間元素。輸出將使用 fmt 包在控制檯上列印中間節點。

演算法

  • 步驟 1 − 建立一個名為 main 的包,並在程式中宣告 fmt(格式化包),其中 main 生成可執行程式碼,fmt 幫助格式化輸入和輸出。

  • 步驟 2 − 建立一個節點結構體,其中包含型別為 int 的值和型別為 node 的 next 指標。

  • 步驟 3 − 建立一個名為 middle_node 的函式,並在該函式中初始化一個計數器變數為 0,以及一個指向連結串列頭部的節點指標。

  • 步驟 4 − 遍歷連結串列,為每個節點遞增計數器,並將節點移動到下一個節點,直到節點到達連結串列末尾。

  • 步驟 5 − 再次將節點初始化為連結串列的頭部。

  • 步驟 6 − 迭代 count/2 次,每次將節點移動到下一個節點。

  • 步驟 7 − 返回節點,該節點將指向連結串列的中間元素。

  • 步驟 8 − 使用 fmt.Println() 函式在主函式中列印接收到的節點,其中 ln 表示換行。

示例

在本例中,我們將使用計數器變數從連結串列中查詢中間元素。

package main
import "fmt"

type Node struct {
   value int
   next  *Node
}

func middle_node(head *Node) *Node {
   count := 0
   node := head
   for node != nil {
      count++
      node = node.next
   }

   node = head
   for i := 0; i < count/2; i++ {
      node = node.next
   }
   return node //here node points to middle element
}

func main() {
   head := &Node{value: 10}    //fill the linked list with required values
   head.next = &Node{value: 20}
   head.next.next = &Node{value: 30}
   head.next.next.next = &Node{value: 40}
   head.next.next.next.next = &Node{value: 50}

   node := middle_node(head)  //obtain the middle element in the node
   fmt.Println("The middle node in the linked list is:", node.value)
}

輸出

The middle node in the linked list is: 30

結論

我們使用兩種方法執行了獲取連結串列中間元素的單次迭代程式。在第一種方法中,我們使用了雙指標法,在第二個示例中,我們使用了計數器變數來跟蹤連結串列的元素。

更新於: 2023年2月22日

211 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告