Check if a singly linked list is a palindrome.

This technical problem deals with singly linked lists, and specifically with checking if a given singly linked list is a palindrome. A palindrome is defined as a word, phrase , or sequence that reads the same backward as forward, and so in this context, a palindrome linked list would be one where the order of the nodes is the same whether you traverse the list from the beginning or from the end. The input to the function is a singly linked list, and the output is a boolean value indicating whether or not the list is a palindrome.

Problem

Given a singly linked list, write a function to check if the list is a palindrome.
Example input:
1 -> 2 -> 3 -> 2 -> 1
Example output:
True

Solution

This solution is in C++. Our A.I. can create solutions in multiple languages.
by kayakane
#include <iostream>
#include <stack>

using namespace std;

struct Node {
    int data;
    Node* next;
};

bool isPalindrome(Node* head) {
    stack<int> s;
    Node* temp = head;
    while (temp != NULL) {
        s.push(temp->data);
        temp = temp->next;
    }
    while (head != NULL) {
        if (head->data != s.top()) {
            return false;
        }
        s.pop();
        head = head->next;
    }
    return true;
}

int main() {
    Node* head = new Node;
    head->data = 1;
    head->next = new Node;
    head->next->data = 2;
    head->next->next = new Node;
    head->next->next->data = 3;
    head->next->next->next = new Node;
    head->next->next->next->data = 2;
    head->next->next->next->next = new Node;
    head->next->next->next->next->data = 1;
    head->next->next->next->next->next = NULL;
    cout << isPalindrome(head) << endl;
    return 0;
}

A.I. Evaluation of the Solution

The candidate's solution correctly implements a function to check if a singly linked list is a palindrome. The candidate uses a stack to store the data from the first half of the list, then compares the data in the second half of the list to the data in the stack. If the data doesn't match, the list is not a palindrome. The candidate's solution is complete and correctly solves the problem. The candidate's approach is sound.

Evaluated at: 2022-12-08 06:15:49