Remove duplicates from unsorted linked list in go
Go program for Remove duplicates from unsorted linked list. Here problem description and explanation.
package main
import "fmt"
// Go Program for
// Delete duplicate nodes in unsorted linked list
type LinkNode struct {
data int
next * LinkNode
}
func getLinkNode(data int) * LinkNode {
return &LinkNode {data,nil}
}
type LinkedList struct {
head * LinkNode
tail * LinkNode
}
func getLinkedList() * LinkedList {
return &LinkedList {nil,nil}
}
// Insert new element at end position
func(this *LinkedList) insert(value int) {
// Create new node
var node * LinkNode = getLinkNode(value)
if this.head == nil {
// Add first node
this.head = node
} else {
// Add new node at the last position
this.tail.next = node
}
// Make new tail
this.tail = node
}
// Display all node value
func(this LinkedList) display() {
if this.head != nil {
fmt.Print("Linked List Element :")
var temp * LinkNode = this.head
for (temp != nil) {
// Display node value
fmt.Print(" ", temp.data)
// Visit to next node
temp = temp.next
}
} else {
fmt.Println("Empty Linked list")
}
}
func(this *LinkedList) removeNode() {
if this.head == nil {
// When linked list empty
fmt.Print("Empty Linked list")
} else {
// Auxiliary variable
var temp * LinkNode = this.head
var hold * LinkNode = nil
var initial * LinkNode = nil
var current * LinkNode = nil
// Outer loop
for (temp != nil) {
current = temp
initial = current.next
// Inner loop
// Remove all node which value is similar to temp node
for (initial != nil) {
if temp.data == initial.data {
// Get remove node
hold = initial
} else {
current = initial
}
// Visit to next node
initial = initial.next
if hold != nil {
current.next = initial
// remove node
hold = nil
}
}
// Visit to next node
temp = temp.next
}
this.tail = current;
}
}
func main() {
// new linked list
var task * LinkedList = getLinkedList()
// Add tested element
task.insert(1)
task.insert(2)
task.insert(9)
task.insert(4)
task.insert(9)
task.insert(3)
task.insert(1)
task.insert(7)
task.insert(2)
task.insert(1)
fmt.Println("\nBefore Delete ")
task.display()
task.removeNode()
fmt.Println("\nAfter Delete ")
task.display()
}
Output
Before Delete
Linked List Element : 1 2 9 4 9 3 1 7 2 1
After Delete
Linked List Element : 1 2 9 4 3 7
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