Determine if a singly linked list is a palindrome.

This problem asks whether a singly linked list is a palindrome, meaning that the data in the list is the same forwards as it is backwards. An example input is provided, along with the expected output.

Problem

Given a singly linked list, determine if it is a palindrome.
Example input:
1->2->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 <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <queue>
#include <deque>
#include <bitset>
#include <iterator>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <numeric>
#include <utility>
#include <limits>
#include <time.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>

using namespace std;

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

Node* newNode(int data) {
    Node* node = new Node;
    node->data = data;
    node->next = NULL;
    return node;
}

void printList(Node* head) {
    while (head != NULL) {
        cout << head->data << " ";
        head = head->next;
    }
    cout << endl;
}

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

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

A.I. Evaluation of the Solution

The candidate's solution correctly determines whether a singly linked list is a palindrome. The candidate uses a fast and slow pointer to find the middle of the list, and then uses a stack to store the first half of the list. The candidate then compares the second half of the list with the values in the stack. This is a correct approach to solving the problem.

Evaluated at: 2022-11-23 16:15:56