美文网首页
234. Palindrome Linked List

234. Palindrome Linked List

作者: YellowLayne | 来源:发表于2017-10-26 18:08 被阅读0次

1.描述

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?

2.分析

将链表后半部分全部翻转;
后半部和前半部分一一对比,若两个节点不相等则不是回文;
还原链表:将后半部分全部翻转。

3.代码

/**
 * 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) {
        if (head == NULL || head->next == NULL) return true;
        
        ListNode *slow = head, *fast = head;
        while (fast->next != NULL && fast->next->next != NULL) {
            slow = slow->next;
            fast = fast->next->next;
        }
        
        slow->next = reverseList(slow->next);
        
        ListNode*  pos = slow->next;
        
        bool ans = true;
        while (pos != NULL) {
            if (head->val != pos->val) {
                ans = false;
            }
            pos = pos->next;
            head = head->next;
        }
        
        slow->next = reverseList(slow->next);
        return ans;
    }
    
    ListNode* reverseList(ListNode* &head) {
        ListNode* pos = head;
        ListNode* tmp;
        head = NULL;
        while (pos != NULL) {
            tmp = pos;
            pos = pos->next;
            tmp->next = head;
            head = tmp;
        }
        return head;
    }
};

相关文章

网友评论

      本文标题:234. Palindrome Linked List

      本文链接:https://www.haomeiwen.com/subject/zlgkpxtx.html