234. 回文链表

题目

 
代码

    /**
     * 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==nullptr||head->next==nullptr)
                return true;
            ListNode* slow=head,*fast=head;
            while(fast->next!=nullptr&&fast->next->next!=nullptr)
            {
                slow=slow->next;
                fast=fast->next->next;
            }
            
            slow->next=reverseList(slow->next);
            slow=slow->next;
            while(slow!=nullptr)
            {
                if(head->val!=slow->val)
                    return false;
                head=head->next;
                slow=slow->next;
            }
            return true;
            
        }
        
        ListNode* reverseList(ListNode* head)
        {
            ListNode* rail=nullptr,*next=nullptr;
            while(head!=nullptr)
            {
                next=head->next;
                head->next=rail;
                rail=head;
                head=next;
            }
            return rail;
        }
       
    };

 
思路

先将链表后半部分逆转,比如[abccba],逆转之后为[abcabc],然后从索引0和链表中间开始同时遍历判断是否相等。
---------------------
作者:李正浩大魔王
来源:CSDN
原文:https://blog.csdn.net/m0_37316917/article/details/82710621
版权声明:本文为博主原创文章,转载请附上博文链接!

posted @ 2019-07-28 22:46  天涯海角路  阅读(111)  评论(0)    收藏  举报