Check if a Linked List is a Palindrome

This function checks whether a given linked list is a palindrome. If the linked list is 1 -> 2 -> 3 -> 2 -> 1, the function will return True.

Problem

Implement a function to check if a given linked list is a palindrome.
Input: 1 -> 2 -> 3 -> 2 -> 1
Output: True

Solution

This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
# Solution:
# The solution is to reverse the linked list and compare it to the original.
# This is optimal because it only requires one pass through the linked list.

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def append(self, data):
        new_node = Node(data)
        if self.head is None:
            self.head = new_node
            return
        last_node = self.head
        while last_node.next:
            last_node = last_node.next
        last_node.next = new_node

    def print_list(self):
        cur_node = self.head
        while cur_node:
            print(cur_node.data)
            cur_node = cur_node.next

    def reverse(self):
        prev = None
        cur = self.head
        while cur:
            nxt = cur.next
            cur.next = prev
            prev = cur
            cur = nxt
        self.head = prev

    def is_palindrome(self):
        self.reverse()
        cur = self.head
        while cur:
            if cur.data != self.head.data:
                return False
            cur = cur.next
            self.head = self.head.next
        return True

llist = LinkedList()
llist.append("R")
llist.append("A")
llist.append("D")
llist.append("A")
llist.append("R")
print(llist.is_palindrome())

A.I. Evaluation of the Solution

The candidate's solution is correct and demonstrates a level of completeness. The approach is to reverse the linked list and compare it to the original. This is optimal because it only requires one pass through the linked list.

Evaluated at: 2022-11-23 18:15:46