234. 回文链表

该博客探讨如何在O(n)时间和O(1)空间复杂度内判断一个链表是否为回文。通过给出示例,如1->2和1->2->2->1,解释了判断过程,并提出了利用找到中间节点并翻转后半段链表进行对比的思路,还提及了使用递归的方法来解决问题。
摘要由CSDN通过智能技术生成

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

示例 1:

输入: 1->2
输出: false

示例 2:

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

进阶:

你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

解答

找到中间节点,翻转后半段链表,再逐个进行对比:

/**
 * 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 || !head->next)
            return true;
        ListNode* mid = middle(head);
        ListNode* h2 = mid->next;
        mid->next = nullptr;
        h2 = reverse(h2);
        while(head && h2){
            if(head->val != h2->val)
                return false;
            head = head->next;
            h2 = h2->next;
        }
        return true;
    }
    ListNode* middle(ListNode* node){
        ListNode *slow, *fast;
        slow = fast = node;
        while(fast->next && fast->next->next){
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }
    ListNode* reverse(ListNode* node){
        ListNode *pre, *cur, *next;
        pre = nullptr;
        cur = next = node;
        while(cur){
            next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
};

递归:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* front;
    bool isPalindrome(ListNode* head) {
        if(!head || !head->next)
            return true;
        front = head;
        return helper(head);
    }
    bool helper(ListNode* node){
        if(!node)
            return true;
        else{
            if(!helper(node->next))
                return false;
            // 执行到此处时,front正好是node对称位置处的节点
            if(front->val != node->val)
                return false;
            front = front->next;
            return true;
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值