您的位置:首页 > 其它

[Leetcode 234, Easy] Palindrome Linked List

2015-07-19 04:59 447 查看
Problem:

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?
Analysis:

Solutions:

C++:

bool isPalindrome(ListNode* head) {
        if(head == NULL || head->next == NULL)
            return true;

        if(head->next->next == NULL)
            return (head->val == head->next->val ? true : false);

        ListNode *fast = head;
        ListNode *slow = head;
        while(fast->next != NULL && fast->next->next != NULL) {
            slow = slow->next;
            fast = fast->next;
            fast = fast->next;
        }

        ListNode *new_head = NULL;
        ListNode *new_cur = NULL;
        ListNode *p_cur = head;
        ListNode *p_temp = slow->next;
        bool till_last_node(fast->next == NULL);
        while(p_cur->next != NULL) {
            ListNode *temp_next = p_cur->next;
            if(new_cur == NULL) {
                new_head = p_cur;
                new_cur = p_cur;
                new_head->next = NULL;
            } else {
                new_head = p_cur;
                new_head->next = new_cur;
                new_cur = new_head;
            }

            p_cur = temp_next;

            if(till_last_node) {
                if(p_cur == slow) {
                    p_cur = p_cur->next;
                    break;
                }
            } else {
                if(p_cur == p_temp)
                    break;
            }
        }

        while(p_cur != NULL) {
            if(p_cur->val != new_cur->val)
                return false;
            p_cur = p_cur->next;
            new_cur = new_cur->next;
        }

        return true;
    }
Java:

Python:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: