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?

思路:找到鏈表中點,拆分後,逆轉後半個鏈表,然後兩個鏈表同時順序遍歷一次。

/**
 * 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* slowNode = head;
        ListNode* fastNode = head;
        
        while(fastNode != NULL&& fastNode->next != NULL){
            fastNode = fastNode->next->next;
            slowNode = slowNode->next;
        }
        
        if(fastNode != NULL)
            slowNode = slowNode->next;
        
        slowNode = reverseList(slowNode);
        while(slowNode != NULL){
            if(head->val != slowNode->val){
                return false;
            }
            head = head->next;
            slowNode = slowNode->next;
        }
        return true;
    }
    
    ListNode* reverseList(ListNode* head){
        if (head == NULL || head->next == NULL)
            return head;
        ListNode* curNode = head->next;
        ListNode* preNode = head;
        preNode->next = NULL;
        ListNode* temp = NULL;
        
        while(curNode != NULL){
            temp = curNode->next;
            curNode->next = preNode;
            preNode = curNode;
            curNode = temp;
        }
        return preNode;
    }
    
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章