链表-回文链表-中等

描述
设计一种方式检查一个链表是否为回文链表。
您在真实的面试中是否遇到过这个题?  是
样例
1->2->1 就是一个回文链表。
挑战

O(n)的时间和O(1)的额外空间。

题目链接

程序


/**
 * Definition of singly-linked-list:
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param head: A ListNode.
     * @return: A boolean.
     */
    /*
    //方法一:栈存储
    bool isPalindrome(ListNode * head) {
        // write your code here
        //不能将链表翻转,因为这样会导致原始链表断裂
        if(head == NULL)
            return true;
        std::stack<int> res;
        ListNode *cur = head;
        while(cur){
            res.push(cur->val);
            cur = cur->next;
        }
        cur = head;
        while(cur){
            if(res.top() != cur->val)
                return false;
            res.pop();
            cur = cur->next;
        }
        return true;
    }
    */
    //O(n)的时间和O(1)的额外空间
    bool isPalindrome(ListNode* head) {
        if (head == NULL || head ->next == NULL) {
            return true;
        }
        ListNode* mid = findmid(head);
        mid->next = reverse(mid->next);
        mid = mid->next;
        while(head!=NULL && mid!=NULL) {
            if(head->val != mid->val) {
                return false;
            }
            head = head->next;
            mid = mid->next;
        }
        return true;
    }
    ListNode * findmid(ListNode * now) {
        ListNode* slow = now;
        ListNode* fast = now ->next;
        while(fast != NULL && fast->next != NULL) {
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }
    ListNode * reverse(ListNode *now) {
        ListNode * pre = NULL;
        while(now!=NULL) {
            ListNode *temp = now->next;
            now->next = pre;
            pre = now;
            now = temp;
        }
        return pre;
    }
};


猜你喜欢

转载自blog.csdn.net/qq_18124075/article/details/81061523