c_cpp 234.回文链表 - 难度易 - 2018.8.9

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 234.回文链表 - 难度易 - 2018.8.9相关的知识,希望对你有一定的参考价值。

/**
 * 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) return NULL;
        ListNode *preNode = NULL;
        ListNode *nextNode;
        while (head->next != NULL) {
            nextNode = head->next; 
            head->next = preNode;
            preNode = head;
            head = nextNode;
        }
        head->next = preNode;
        return head;
    }
    bool isPalindrome(ListNode* head) {
        if (head == NULL) return true;

        ListNode *slowNode = head;
        ListNode *fastNode = head;
        
        while (fastNode->next 
                && fastNode->next->next) {
            slowNode = slowNode->next;
            fastNode = fastNode->next->next;
        }

        ListNode *nextHeadNode = slowNode->next;
        if (nextHeadNode == NULL) {
            return true;
        }

        slowNode->next = NULL;

        ListNode *comparedHeadNode = reverseList(nextHeadNode);
        
        while (head != NULL && comparedHeadNode != NULL) {
            if (head->val != comparedHeadNode->val) return false;
            head = head->next;
            comparedHeadNode = comparedHeadNode->next;       
        }

        return true;
    }
};

以上是关于c_cpp 234.回文链表 - 难度易 - 2018.8.9的主要内容,如果未能解决你的问题,请参考以下文章

234. 回文链表

LeetCode234:回文链表

LeetCode 234——回文链表

234. 回文链表

LeetCode 234——回文链表

276.LeetCode | 234. 回文链表