【简单算法】24.回文链表

题目:

请检查一个链表是否为回文链表。

进阶:
你能在 O(n) 的时间和 O(1) 的额外空间中做到吗?

解题思路:

1.非递归。直接将链表中的元素拷贝到数组中,然后比较数组是否为回文数组即可。

2.找到链表的中间节点,从中间节点开始,对聊表的后半部分进行反转,比较链表前半部分和后半部分,是否元素依次相等即可。

/**
 * 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 * newHead = reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        
        return newHead;
    }
    
    bool isPalindrome1(ListNode* head) {
       if(head == NULL || head->next == NULL){
           return true;
       }
       
       ListNode * tail = reverseList(head->next);
       if(tail->val != head->val){
           return false;
       }else{
           return isPalindrome(tail->next);
       }
        
    }
    
    int length(ListNode * head){
        int cnt = 0;
        while(head){
            head = head->next;
            cnt++;
        }
        
        return cnt;
    }
    
    bool isPalindrome(ListNode* head) {
        int len = length(head);
        int target = len%2?(len+1)/2:len/2;
        ListNode * slow = head;
        ListNode * fast = head;
        
        if(head == NULL || head->next == NULL){
            return true;
        }
        
        for(int i = 0;i < target;++i){
            head = head->next;
        }
        
        fast = reverseList(head);
        for(int i = 0;i < len/2;++i){
            if(fast->val != slow->val){
                return false;
            }else{
                fast = fast->next;
                slow = slow->next;
            }
        }
        
        return true;
    }
};
原文地址:https://www.cnblogs.com/mikemeng/p/8985069.html