[LeetCode 解题报告]234. Palindrome Linked List

Given a singly linked list, determine if it is a palindrome.

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

Follow up:
Could you do it in O(n) time and O(1) space?

/**
 * 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* fast = head, *slow = head;
        while (fast->next && fast->next->next)  {
            fast = fast->next->next;
            slow = slow->next;
        }
        
        ListNode* last = slow->next;
        while (last->next) {
            ListNode* tmp = last->next;
            last->next = tmp->next;
            tmp->next = slow->next;
            slow->next = tmp;
        }
        
        ListNode* pre = head;
        while (slow->next) {
            slow = slow->next;
            if (pre->val != slow->val)
                return false;
            pre = pre->next;
        }
        return true;
    }
};
    
发布了467 篇原创文章 · 获赞 40 · 访问量 45万+

猜你喜欢

转载自blog.csdn.net/caicaiatnbu/article/details/104216241