0
点赞
收藏
分享

微信扫一扫

力扣234. 回文链表

草原小黄河 2022-04-01 阅读 48

234. 回文链表
教程

解题思路

代码

/**
 * 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:
    bool isPalindrome(ListNode* head) {
        ListNode *fast = head , *slow = head;
        while(fast!=nullptr && fast->next != nullptr){
            fast=fast->next->next;
            slow=slow->next;
        } 
        if(fast!=nullptr){//说明是奇数个节点个数
            //此刻slow正指向最中间的那个节点
            slow=slow->next;//我们将slow后移一位,不把中间节点算入我们要反转的那段链表中
        }
        slow = reverseList(slow);
        fast = head;
        while(slow!=nullptr){//一对一
            if(fast->val != slow->val){
                return false;
            }
            fast=fast->next;
            slow=slow->next;
        }
            return true;
    }
    ListNode* reverseList(ListNode* head) {
        ListNode *pre = nullptr;
        ListNode *cur = head;
        while(cur!=nullptr){//当cur指针指向空,结束循环
            ListNode *p = cur->next;//p存放cur的下一个节点
            cur->next = pre;//逆转
            //接下来两行,pre和cur按照次序进行前移
            pre = cur;
            cur = p;
        }
        return pre;
    }
};
举报

相关推荐

0 条评论