• Leetcode [234] 回文链表 回文 链表


    /*
     * @lc app=leetcode.cn id=234 lang=cpp
     *
     * [234] 回文链表
     *
     * https://leetcode-cn.com/problems/palindrome-linked-list/description/
     *
     * algorithms
     * Easy (47.14%)
     * Likes:    983
     * Dislikes: 0
     * Total Accepted:    246.9K
     * Total Submissions: 518K
     * Testcase Example:  '[1,2,2,1]'
     *
     * 请判断一个链表是否为回文链表。
     * 
     * 示例 1:
     * 
     * 输入: 1->2
     * 输出: false
     * 
     * 示例 2:
     * 
     * 输入: 1->2->2->1
     * 输出: true
     * 
     * 
     * 进阶:
     * 你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
     * 
     */
    
    // @lc code=start
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode() : val(0), next(nullptr) {}
     *     ListNode(int x) : val(x), next(nullptr) {}
     *     ListNode(int x, ListNode *next) : val(x), next(next) {}
     * };
     */

    思路:

    如何高效判断回文单链表?

    1、通过快慢指针查找链表的中点,如果fast指针没有指向null,说明链表长度为奇数,slow还要再前进一步

     2、slow开始反转后面的链表,现在就可以开始比较回文串了

    class Solution {
    public:
        bool isPalindrome(ListNode* head) {
            ListNode *fast=head;
            ListNode *slow=head;
            while(fast!=NULL&&fast->next!=NULL)
            {
                slow=slow->next;
                fast=fast->next->next;
            }
            if(fast!=NULL) slow=slow->next;
            ListNode *right=reverse(slow);
            ListNode *left=head;
            while(right!=NULL)
            {
                if(left->val!=right->val) return false;
                left=left->next;
                right=right->next;
            }
            return true;
        }
        ListNode* reverse(ListNode *head)
        {
            if(!head) return head;
            ListNode* pre=NULL;
            ListNode* cur=head;
            while(cur!=NULL)
            {
                ListNode* next=cur->next;
                cur->next=pre;
                pre=cur;
                cur=next;
            }
            return pre;
        }
    };
    联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
  • 相关阅读:
    javascript的语法作用域你真的懂了吗
    网页的三种布局(固定宽度式,流体式,弹性式)
    css3系列之animation
    跟我学习css3之transition
    函数调用你知道几种方法
    javascript的那些事儿你都懂了吗
    css3的那些高级选择器二
    [转]影响Cache的几个HTTP头信息
    CSS属性合写
    defer 与 async
  • 原文地址:https://www.cnblogs.com/zl1991/p/14782553.html
Copyright © 2020-2023  润新知