zoukankan      html  css  js  c++  java
  • leetcode234 C++ 28ms 回文链表

    /**
     * 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* p_len = head;
            int len = 0;
    
            while(p_len != nullptr){
                p_len = p_len->next;
                len++;
            }
    
            ListNode* right = head;
            ListNode* curr = head;
            ListNode* prev = nullptr;
    
            for(int i=0;i<(len/2);i++){
                right = curr->next;
                curr->next = prev;
                prev = curr;
                curr = right;
            }
            if(len%2 == 1){
                right = right->next;
            }
            while(prev !=nullptr && right != nullptr){
                if(prev->val != right->val){
                    return false;
                }
                prev=prev->next;
                right=right->next;
            }
    
            return true;
    
    
        }
    };
    

    思路是:
    先遍历第一遍得到长度。
    取两个指针,第一个指针配合prev指针将前半部分反转,第二个指针顺势移到链表的中间右边的节点。
    这样两个指针分别从中间向左右移动,互相比较。

  • 相关阅读:
    python 迭代器
    python 装饰器
    python 函数进阶
    python 函数
    python文件操作
    python 集合 深浅拷贝
    python基础之循环
    python基础之字典
    python基础之操作列表
    python基础之列表
  • 原文地址:https://www.cnblogs.com/theodoric008/p/9362919.html
Copyright © 2011-2022 走看看