Delete last node of linked list in go

Go program for Delete last node of linked list. Here problem description and explanation.

package main
import "fmt"
/*
    Go program for
    Delete the last node of singly 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
    tail * LinkNode
}
func getSingleLL() * SingleLL {
    return &SingleLL {nil,nil}
}
// Add new node at the end of linked list
func(this *SingleLL) addNode(value int) {
    // Create a new node
    var node * LinkNode = getLinkNode(value)
    if this.head == nil {
        this.head = node
    } else {
        this.tail.next = node
    }
    // Set new last node
    this.tail = node
}
// Display linked list element
func(this SingleLL) display() {
    if this.head == nil {
        fmt.Println("Empty Linked List")
        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.Println("NULL")
}
// Delete last node of singly linked list
func(this *SingleLL) deleteLastNode() {
    if this.head == nil {
        fmt.Println("Empty Linked List")
        return
    } else {
        var temp * LinkNode = this.head
        var find * LinkNode = nil
        // Find second last node
        for (temp.next != nil) {
            find = temp
            temp = temp.next
        }
        if find == nil {
            // Delete head node of linked list
            this.head = nil
            this.tail = nil
        } else {
            // Set new last node
            this.tail = find
            find.next = nil
        }
    }
}
func main() {
    var sll * SingleLL = getSingleLL()
    // Linked list
    // 1 → 2 → 3 → 4 → 5 → 6 → NULL
    sll.addNode(1)
    sll.addNode(2)
    sll.addNode(3)
    sll.addNode(4)
    sll.addNode(5)
    sll.addNode(6)
    fmt.Println("Before Delete ")
    sll.display()
    sll.deleteLastNode()
    fmt.Println("After Delete ")
    sll.display()
}

Output

Before Delete
1 → 2 → 3 → 4 → 5 → 6 → NULL
After Delete
1 → 2 → 3 → 4 → 5 → 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