Palindrome

2.6 Palindrome: Implement a function to check if a linked list is a palindrome.

bool isPalindrome(Node *head) {
    if (!head) return nullptr;
    stack<Node*> s;
    Node *iter = head;
    s.push(iter);

    while (iter->next) {
        s.push(iter->next);
        iter = iter->next;
    }

    iter = head;
    int count = 0;
    while (count < ceil(s.size() / 2)) {
        if (iter->value != s.top()->value)
            return false;
        iter = iter->next;
        s.pop();
        count++;
    }

    return true;
}

int main()
{
    LinkedList LL1;

    vector<int> stuff = {1,2,3,3,2,1};
    for (auto i : stuff) 
        LL1.insert(i);

    LL1.print();
    cout << boolalpha << isPalindrome(LL1.front) << endl;

    LinkedList LL2;
    stuff = { 1,1,3,3,2,1 };
    for (auto i : stuff)
        LL2.insert(i);
    LL2.print();
    cout << boolalpha << isPalindrome(LL2.front) << endl;

    LinkedList LL3;
    stuff = { 1,2,3,4,3,2,1 };
    for (auto i : stuff)
        LL3.insert(i);
    LL3.print();
    cout << boolalpha << isPalindrome(LL3.front) << endl;
}

Last updated