Tuesday, July 5, 2016

Palindrome Linked lists

Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?

Solution:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        ListNode* temp = head;
        stack<int> st;
        while (temp != NULL) {
            st.push(temp->val);
            temp = temp -> next;
        }
     
        while (!st.empty()) {
            if (st.top() != head -> val) {
                return false;
            } else {
                st.pop();
                head = head -> next;
            }
        }
        return true;
    }
    // For o(1) space,
    // 1. Find pointer to center node.
    // 2. Reverse the link list from center node.
    // Finally compare.
};

======== o(1) =======

 ListNode * reverse(ListNode *head) {
        ListNode *cur = head, *pre = NULL, *next = NULL;
       
        while (cur != NULL) {
            next = cur -> next;
            cur -> next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

    bool isPalindrome(ListNode* head) {
        ListNode *trav = head, *center = head;
       
        if (head == NULL || head -> next == NULL) {
            return true;
        }
       
        while (trav != NULL) {
            if (trav -> next != NULL) {
                trav = trav -> next -> next;
                center = center -> next;
            } else {
                trav = NULL;
            }
        }
       
        ListNode *end = reverse(center);
       
        while (end != NULL) {
            if (head -> val != end -> val) {
                return false;
            }
            head = head -> next;
            end = end -> next;
        }
        return true;
    }
};

No comments:

Post a Comment