Check if a doubly linked list is form of palindrome in golang
Go program for Detect palindrome in doubly linked list. Here problem description and explanation.
package main
import "fmt"
// Go program for
// Check if palindrome exists in doubly linked list
// This is Linked List Node
type LinkNode struct {
data int
next * LinkNode
prev * LinkNode
}
func getLinkNode(data int) * LinkNode {
// return new LinkNode
return &LinkNode {
data,
nil,
nil,
}
}
type DoublyLinkedList struct {
head * LinkNode
tail * LinkNode
}
func getDoublyLinkedList() * DoublyLinkedList {
// return new DoublyLinkedList
return &DoublyLinkedList {
nil,
nil,
}
}
// Insert new node at end position
func(this *DoublyLinkedList) insert(value int) {
// Create a node
var node * LinkNode = getLinkNode(value)
if this.head == nil {
// Add first node
this.head = node
this.tail = node
return
}
// Add node at last position
this.tail.next = node
node.prev = this.tail
this.tail = node
}
// Display node element of doubly linked list
func(this DoublyLinkedList) display() {
if this.head == nil {
fmt.Println("Empty Linked List")
} else {
fmt.Print("Linked List Head to Tail :")
// Get first node of linked list
var temp * LinkNode = this.head
// iterate linked list
for (temp != nil) {
// Display node value
fmt.Print(" ", temp.data)
// Visit to next node
temp = temp.next
}
fmt.Print("\nLinked List Tail to Head :")
// Get last node of linked list
temp = this.tail
// iterate linked list
for (temp != nil) {
// Display node value
fmt.Print(" ", temp.data)
// Visit to prev node
temp = temp.prev
}
}
}
func(this DoublyLinkedList) isPalindrome() bool {
if this.head == nil {
// When empty linked list
return false
}
var first * LinkNode = this.head
var last * LinkNode = this.tail
for (last != nil && first != nil && first != last) {
if first.data != last.data {
// When node value are not same
return false
}
if first.next == last {
// When get last pair
if first.data == last.data {
// When pair value is same
return true
}
// When last middle node not same
return false
}
// Visit to next node
first = first.next
// Visit to previous node
last = last.prev
}
return true
}
func main() {
var dll * DoublyLinkedList = getDoublyLinkedList()
// Insert following linked list nodes
dll.insert(1)
dll.insert(2)
dll.insert(4)
dll.insert(3)
dll.insert(4)
dll.insert(2)
dll.insert(1)
// Display all node
dll.display()
// Test A
if dll.isPalindrome() == true {
fmt.Println("\nYes")
} else {
fmt.Println("\nNo")
}
// Add new element
dll.insert(1)
dll.display()
// Test B
if dll.isPalindrome() == true {
fmt.Println("\nYes")
} else {
fmt.Println("\nNo")
}
}
Output
Linked List Head to Tail : 1 2 4 3 4 2 1
Linked List Tail to Head : 1 2 4 3 4 2 1
Yes
Linked List Head to Tail : 1 2 4 3 4 2 1 1
Linked List Tail to Head : 1 1 2 4 3 4 2 1
No
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