当前位置 博文首页 > cpb____的博客:[C++]Leetcode234.回文链表

    cpb____的博客:[C++]Leetcode234.回文链表

    作者:[db:作者] 时间:2021-08-14 21:08

    234.回文链表

    题目:请判断一个链表是否为回文链表。

    示例 1: 输入: 1->2 输出: false

    示例 2: 输入: 1->2->2->1 输出: true

    思路:设置快慢指针进行移动,直至慢指针到达中间位置。接着定义三个指针curnode、nextnode、temp来进行链表反转。最后while循环在两段链表不为空时循环,判断每个位置的元素是否相等,并移动指针

    
    
    class Solution {
    public:
        bool isPalindrome(ListNode* head) 
        {
            if(!head || !head->next) return true;
            ListNode * fast = head;
            ListNode * slow = head;
            while(fast && fast->next)
            {
                fast = fast->next->next;
                slow = slow->next;
            }
            ListNode * curnode = slow;
            ListNode * nextnode = slow->next;
            while(nextnode)
            {
                ListNode * temp = nextnode->next;
                nextnode->next = curnode;
                curnode = nextnode;
                nextnode = temp;
            }
            slow->next = NULL;
            while(head && curnode)
            {
                if(head->val != curnode->val) return false;
                head = head->next;
                curnode = curnode->next;
            }
            return true;
        }
    };
    

    [[C++]Leetcode超高效刷题顺序及题目详解笔记(持续更新中)]

    cs