Delete duplicate nodes from sorted linked list in go

Go program for Delete duplicate nodes from sorted linked list. Here problem description and explanation.

package main
import "fmt"
/*
    Go program for
    Delete duplicate nodes in sorted 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
    }
    this.tail = 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.Println(" NULL")
}
// Remove the duplicate nodes from sorted singly linked list
func(this SingleLL) deleteDuplicate() {
    if this.head == nil {
        return
    } else {
        // Auxiliary variables
        var temp * LinkNode = this.head.next
        var current * LinkNode = this.head
        var hold * LinkNode = nil
        // Find and remove duplicate
        for (temp != nil) {
            // Check duplicate node 
            if current.data == temp.data {
                //  When node key are same
                hold = temp
            } else {
                // When node key are not same
                current = temp
            }
            // Visit to next node
            temp = temp.next
            if hold != nil {
                // Modified link value
                current.next = temp
                hold = nil
            } else {
                // Change last node
                this.tail = current
            }
        }
    }
}
func main() {
    var sll * SingleLL = getSingleLL()
    // Sorted Linked list node
    //  1 → 1 → 2 → 3 → 4 → 4 → 4 → 5 → 6 → 7 → NULL
    sll.addNode(1)
    sll.addNode(1)
    sll.addNode(2)
    sll.addNode(3)
    sll.addNode(4)
    sll.addNode(4)
    sll.addNode(4)
    sll.addNode(5)
    sll.addNode(6)
    sll.addNode(7)
    fmt.Println(" Before Delete")
    sll.display()
    sll.deleteDuplicate()
    fmt.Println(" After Delete")
    // 1 → 2 → 3 → 4 → 5 → 6 → 7 → NULL
    sll.display()
}

Output

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







© 2022, kalkicode.com, All rights reserved