To check if a linked list is a palindrome, you can use the following approach:
- Traverse the linked list and push all its elements onto a stack.
- Traverse the linked list again, and for each element, pop an element from the stack and compare it to the current element. If all the elements match, then the linked list is a palindrome. Otherwise, it is not a palindrome.
import java.util.Stack
class Node(var data: Int) {
var next: Node? = null
}
Firstly import Stack in program. it will be used to store the data of linked list.
Node
class represents a node in the linked list, with an integer data
and a next
reference to the next node in the list.
fun isPalindrome(head: Node?): Boolean {
val stack = Stack<Int>()
var temp = head
while (temp != null) {
stack.push(temp.data)
temp = temp.next
}
temp = head
while (temp != null) {
val top = stack.pop()
if (temp.data != top) {
return false
}
temp = temp.next
}
return true
}
In this code, the isPalindrome
function takes a head
parameter, which is a reference to the head node of a linked list. The function returns true
if the linked list is a palindrome, and false
otherwise.
The function first creates a stack and pushes all the elements of the linked list onto it by traversing the list. It then traverses the list again, popping elements from the stack and comparing them to the current element. If any elements don’t match, the function returns false
. If all elements match, the function returns true
.
import java.util.Stack
class Node(var data: Int) {
var next: Node? = null
}
fun isPalindrome(head: Node?): Boolean {
val stack = Stack<Int>()
var temp = head
while (temp != null) {
stack.push(temp.data)
temp = temp.next
}
temp = head
while (temp != null) {
val top = stack.pop()
if (temp.data != top) {
return false
}
temp = temp.next
}
return true
}
fun main() {
// create a palindrome linked list
val head1 = Node(1)
head1.next = Node(2)
head1.next?.next = Node(3)
head1.next?.next?.next = Node(2)
head1.next?.next?.next?.next = Node(1)
// check if it's a palindrome
val isPalindrome1 = isPalindrome(head1)
if (isPalindrome1) {
println("The linked list is a palindrome")
} else {
println("The linked list is not a palindrome")
}
// create a non-palindrome linked list
val head2 = Node(1)
head2.next = Node(2)
head2.next?.next = Node(3)
head2.next?.next?.next = Node(4)
head2.next?.next?.next?.next = Node(5)
// check if it's a palindrome
val isPalindrome2 = isPalindrome(head2)
if (isPalindrome2) {
println("The linked list is a palindrome")
} else {
println("The linked list is not a palindrome")
}
}
In the main
function, two linked lists are created, one of which is a palindrome and the other is not. The isPalindrome
function is called for each linked list, and the result is printed to the console.