Sorted order insertion of linked list in go

Go program for Sorted order insertion of linked list. Here problem description and explanation.

package main
import "fmt"
/*
    Go program for
    Add node in sorted order of linked list
*/
// Linked list node
type LinkNode struct {
    data int
    next * LinkNode
}
func getLinkNode(data int) * LinkNode {

    return &LinkNode {data, nil}
}
type SingleLL struct {
    head * LinkNode
}
func getSingleLL() * SingleLL {

    return &SingleLL {nil}
}
// Add new node in sorted order
func(this *SingleLL) sortedAdd(data int) {
    // Create new node
    var node * LinkNode = getLinkNode(data)
    if this.head == nil || this.head.data >= data {
        // When linked list empty
        // or new nodes are adding at beginning
        node.next = this.head
        this.head = node
    } else {
        var temp * LinkNode = this.head
        // Find position to add new node
        for (temp.next != nil && temp.next.data < data) {
            // Visit to next node
            temp = temp.next
        }
        node.next = temp.next
        // Add new node
        temp.next = node
    }
}
// Display linked list element
func(this SingleLL) 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 * SingleLL = getSingleLL()
    // Add Linked list node
    sll.sortedAdd(1)
    sll.sortedAdd(-3)
    sll.sortedAdd(9)
    sll.sortedAdd(4)
    sll.sortedAdd(11)
    sll.sortedAdd(-7)
    fmt.Print("Linked List \n")
    // -7 → -3 → 1 → 4 → 9 → 11 → NULL
    sll.display()
}

Output

 Linked List
 -7 → -3 → 1 → 4 → 9 → 11 → 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