判断单链表是否为回文链表

给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。要求用 O(n) 时间复杂度和 O(1) 空间复杂度解决。

在这里插入图片描述

/**
 * 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.先遍历整个链表得出长度len
 2.再将fast节点移至链表的中间
 3.反转链表的后半段
 4.对比链表的前半段和反转后的后半段链表值,出现不相等的就表示不是回文链表,否则就是回文链表
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *node = nullptr;
        while(head) {
            ListNode* tmp = head->next;
            head->next = node;
            node = head;
            head = tmp;
        }
        return node;
    }
    bool isPalindrome(ListNode* head) {
        int len = 0;
        ListNode* node = head;
        while(node) {
            len++;
            node = node->next;
        }
        ListNode* fast = head;
        for(int i = 0; i < len/2; i++) {
            fast = fast->next;
        }
        ListNode* new_head = reverseList(fast);
        while(head && new_head) {
            if(head->val != new_head->val) {
                return false;
            }
            new_head = new_head->next;
            head = head->next;
        }
        return true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值