Sunday, August 18, 2013

linked list palindrome


/* From Cracking the Coding Interview 2-7 */
/* Implement a function to check if a linked list is a palindrome. */

void deleteLinkedList(node *);
bool isPalindrome(node *);

void deleteLinkedList(node * head) {
    while (head != nullptr) {
        node * p = head;
        head = p->next;
        delete p;
    }
}

bool isPalindrome(node * head) {
    if (head == nullptr) {
        return false;
    }
    node * p = head;
    node * rHead = nullptr; // use a copy of reversed list
    while (p != nullptr) {
        node * n = new node(p->data);
        n->next = rHead;
        rHead = n;
        p = p->next;
    }
    p = head;
    node * p2 = rHead;
    while (p != nullptr) {
        if (p->data != p2->data) {
            deleteLinkedList(rHead);
            return false;
        }
        p = p->next;
        p2 = p2->next;
    }
    deleteLinkedList(rHead);
    return true;

}

No comments:

Post a Comment