美文网首页Leetcode
Leetcode 234. Palindrome Linked

Leetcode 234. Palindrome Linked

作者: SnailTyan | 来源:发表于2018-09-29 18:10 被阅读2次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Palindrome Linked List

    2. Solution

    /**
     * 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 || !head->next) {
                return true;
            }
            ListNode* current = head;
            ListNode* mid = head;
            while(current && current->next) {
                mid = mid->next;
                current = current->next->next;
            }
            ListNode* pre = mid;
            current = mid->next;
            mid->next = nullptr;
            ListNode* next = nullptr;
            while(current) {
                next = current->next;
                current->next = pre;
                pre = current;
                current = next;
            }
            current = head;
            while(pre) {
                if(pre->val != current->val) {
                    return false;
                }
                pre = pre->next;
                current = current->next;
            }
            return true;
        }
    };
    

    Reference

    1. https://leetcode.com/problems/palindrome-linked-list/description/

    相关文章

      网友评论

        本文标题:Leetcode 234. Palindrome Linked

        本文链接:https://www.haomeiwen.com/subject/jduboftx.html