Insert node at middle of linked list in go

Suppose we are inserted the following (1, 2, 3, 4, 5, 6, 7) node in a sequence. In this post are implement second approach.

insert linked list node in middle position
package main
import "fmt"
// Go Program for
// Insert linked list element at middle position

// Linked list node
type LinkNode struct {
    data int
    next * LinkNode
}
func getLinkNode(data int) * LinkNode {

    return &LinkNode {data,nil}
}
type LinkedList struct {
    head * LinkNode
}
func getLinkedList() * LinkedList {

    return &LinkedList {nil}
}
// Insert node in middle position
func(this *LinkedList) insert(value int) {
    // Create a new node
    var node * LinkNode = getLinkNode(value)
    if this.head == nil {
        // First node
        this.head = node
    } else {
        var temp * LinkNode = this.head
        var middle * LinkNode = this.head
        // Find the middle node
        for (temp.next != nil && temp.next.next != nil) {
            temp = temp.next.next
            middle = middle.next
        }
        // add node
        node.next = middle.next
        middle.next = node
    }
}
// Display linked list element
func(this LinkedList) display() {
    if this.head == nil {
        return
    }
    var temp * LinkNode = this.head
    // iterating linked list elements
    for (temp != nil) {
        fmt.Print(temp.data, " → ")
        // Visit to next node
        temp = temp.next
    }
    fmt.Print("NULL\n")
}
func main() {
    var sll * LinkedList = getLinkedList()
    // Add node
    sll.insert(1)
    sll.insert(2)
    sll.insert(3)
    sll.insert(4)
    sll.insert(5)
    sll.insert(6)
    sll.insert(7)
    // 1 → 3 → 5 → 7 → 6 → 4 → 2 → NULL
    sll.display()
}
 1 → 3 → 5 → 7 → 6 → 4 → 2 → NULL


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved