leetcode234 回文链表(Easy,不简单)

题目来源:leetcode234 回文链表

题目描述:

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true

进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

解题思路:

方法一:借助一个数组保存链表结点值,再双指针判断是否是回文。

/**
 * 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) {
        vector<int> t;
        while(head!=NULL){
            t.push_back(head->val);
            head=head->next;
        }
        int i=0,j=t.size()-1;
        while(i<j){
            if(t[i]!=t[j]) return false;
            i++;
            j--;
        }
        return true;
    }
};

方法二:借助快慢指针找到链表的中点,再将后半部分链表翻转,再判断前后是否相同,相同则为回文链表

/**
 * 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) {
        ListNode *slow=head,*fast=head;
        while(fast&&fast->next){
            slow=slow->next;
            fast=fast->next->next;
        }
        ListNode * p=reverse(slow);
        ListNode * last=p;
        ListNode * pre=head;
        while(last&&pre){
            if(pre->val!=last->val) return false;
            pre=pre->next;
            last=last->next;
        }
        return true;
    }
    ListNode * reverse(ListNode *head){
        if(head==NULL||head->next==NULL) return head;
        ListNode * newhead=reverse(head->next);
        head->next->next=head;
        head->next=NULL;
        return newhead;
    }
};
原文地址:https://www.cnblogs.com/yjcoding/p/13267261.html