zoukankan      html  css  js  c++  java
  • 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和链表中间开始同时遍历判断是否相等。

    https://github.com/li-zheng-hao
  • 相关阅读:
    两种&
    安装版Windows是必须的
    检验CSS3.0兼容性的有趣东东
    Quadro和Geforce系列的区别
    ECMAScript
    多拉A梦的CSS(6) :not
    多拉A梦的CSS(1) Transform
    表单
    关于a元素的伪类
    多拉A梦的CSS(4) gradient
  • 原文地址:https://www.cnblogs.com/lizhenghao126/p/11053631.html
Copyright © 2011-2022 走看看