LeetCode-E-Palindrome Linked List

題意

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?

Subscribe to see which companies asked this question.

Show Tags
Show Similar Problems

解法

雙指針,翻轉後半段鏈表,和前半段做對比

實現

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head == NULL || head->next == NULL) return head;
        ListNode* cur = head;
        while(cur->next != NULL){
            ListNode* next = cur->next;
            cur->next = next->next;
            next->next = head;
            head = next;
        }
        return head;
    }
    bool isPalindrome(ListNode* head) {
        if(head == NULL || head->next == NULL) return true;
        ListNode* fast = head;
        ListNode* slow = head;
        ListNode* pre = NULL;
        while(fast != NULL && fast->next != NULL){
            fast = fast->next->next;
            pre = slow;
            slow = slow->next;
        }
        pre->next = NULL;
        if(fast != NULL && fast->next == NULL) slow = slow->next;
        ListNode* rhead = reverseList(slow);
        ListNode* p = head;
        ListNode* q = rhead;
        while(q != NULL && p != NULL){
            if(p->val != q->val) return false;
            p = p->next;
            q = q->next;
        }
        if(q != NULL || p != NULL) return false;
        return true;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章