• 回文链表


    题目链接:https://leetcode-cn.com/problems/palindrome-linked-list/
    题目描述:

    题解:

    /**
     * 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) {}
     * };
     */
    class Solution {
    public:
        ListNode* reverseList(ListNode* node)
        {
            ListNode *pre = nullptr;
            ListNode *cur = node;
            ListNode *tail;
            while(cur != nullptr)
            {
                tail = cur->next;
                cur->next = pre;
                pre = cur;
                cur = tail;
            }
            return pre;
        }
        bool isPalindrome(ListNode* head) {
            if(!head || !head->next)
                return true;
            ListNode* fast = head;
            ListNode* slow = head;
            ListNode* prev;
            //快慢指针找中点
            while(fast != nullptr && fast->next != nullptr)
            {
                slow = slow->next; 
                fast = fast->next->next;
            }
            //链表节点奇偶处理
            if(fast != nullptr)
                prev = slow->next;
            else
                prev = slow;
            //后半部节点反转
            prev = reverseList(prev);
            while(prev && head)
            {
                if(head->val != prev->val)
                    return false;
                head = head->next;
                prev = prev->next;
    
            }
            return true;
        }
    };
    
    
  • 相关阅读:
    严格模式
    排序,求最大值最小值
    原型继承
    android 系统
    BASE64Decoder
    jstl
    list  遍历
    2015GitWebRTC编译实录9
    2015GitWebRTC编译实录8
    2015GitWebRTC编译实录7
  • 原文地址:https://www.cnblogs.com/ZigHello/p/14885726.html
Copyright © 2020-2023  润新知