Go語言程式,用於在第 i 個索引節點插入節點,當索引位於連結串列的第 0 個位置時。


示例

解決此問題的方法

步驟 1 - 定義一個接受連結串列頭的方法。

步驟 2 - 如果 head == nil,則建立一個新節點並將其設為 head,並將其作為新的 head 返回。

步驟 3 - 當 index == 0 時,更新 head。

步驟 4 - 從其頭部迭代給定的連結串列。此外,初始化 preNode,它將儲存前一個節點的地址。

步驟 5 - 如果索引 i 與給定索引匹配,則刪除該 node.next,並中斷迴圈。

步驟 6 - 在迴圈結束時返回。

示例

 即時演示

package main
import "fmt"
type Node struct {
   value int
   next *Node
}
func NewNode(value int, next *Node) *Node{
   var n Node
   n.value = value
   n.next = next
   return &n
}
func TraverseLinkedList(head *Node){
   temp := head
   for temp != nil {
      fmt.Printf("%d ", temp.value)
      temp = temp.next
   }
   fmt.Println()
}
func InsertNodeAtIthIndex(head *Node, index, data int) *Node{
   if head == nil{
      head = NewNode(data, nil)
      return head
   }
   if index == 0{
      newNode := NewNode(data, nil)
      newNode.next = head
      head = newNode
      return head
   }
   i := 0
   temp := head
   preNode := temp
   for temp != nil {
      if i == index{
         newNode := NewNode(data, nil)
         preNode.next = newNode
         newNode.next = temp
         break
      }
      i++
      preNode = temp
      temp = temp.next
   }
   return head
}
func main(){
   head := NewNode(30, NewNode(10, NewNode(40, NewNode(40, nil))))
   fmt.Printf("Input Linked list is: ")
   TraverseLinkedList(head)
   index := 0
   head = InsertNodeAtIthIndex(head, index, 5)
   fmt.Printf("Inserting new node at %dth index, Linked List is: ", index)
   TraverseLinkedList(head)
}

輸出

Input Linked list is: 30 10 40 40
Inserting new node at 0th index, Linked List is: 5 30 10 40 40

更新於: 2021年3月18日

342 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告