The singly-linked list is a Palindrome?

JavaScript

Check if a singly linked list is a palindrome:

To check if a singly linked list is a palindrome, you can follow these steps:

1. Traverse the linked list and push each node's value into an array.

2. Use two pointers technique to compare elements from both ends of the array:

Start with one pointer at the beginning of the array and the other pointer at the end.

Move the pointers towards each other while comparing the elements they point to.

If at any point, the elements are not equal, the linked list is not a palindrome.

3. If the pointers meet or cross each other without finding any unequal elements, the linked list is a palindrome.

Here's how you can implement this algorithm in JavaScript:

js Copy Code
class ListNode {
    constructor(val, next = null) {
        this.val = val;
        this.next = next;
    }
}

function isPalindrome(head) {
    let array = [];
    let current = head;

    // Traverse the linked list and push each node's value into the array
    while (current) {
        array.push(current.val);
        current = current.next;
    }

    // Use two pointers to compare elements from both ends of the array
    let left = 0;
    let right = array.length - 1;

    while (left < right) {
        if (array[left] !== array[right]) {
            return false;
        }
        left++;
        right--;
    }

    return true;
}

// Example usage:
// Create a linked list: 1 -> 2 -> 3 -> 2 -> 1
const head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(2);
head.next.next.next.next = new ListNode(1);

console.log(isPalindrome(head)); // Output: true
Output:
true

Explanation:

The 'ListNode' class represents each node in the linked list. The 'isPalindrome' function takes the head of the linked list as input and returns 'true' if the linked list is a palindrome, and 'false' otherwise.

It traverses the linked list to construct an array of node values, and then uses the two pointers technique to compare elements from both ends of the array.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.