Leetcode 每日一题——234. 回文链表

234. 回文链表

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

在这里插入图片描述
链表问题如果不涉及其他数据结构的话还是相对简单的,这道题很容易想到使用快慢指针,找到尾节点,翻转后半段链表,然后判断回文特性。具体C++的实现过程如下:

/**
 * 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) {
        ListNode *fast=head;
        ListNode *slow=head;
        while(fast!=NULL && fast->next!=NULL)
        {
            fast=fast->next->next;
            slow=slow->next;
        }
        fast=NULL;
        while(slow)
        {
            ListNode *tmpnext=slow->next;
            slow->next=fast;
            fast=slow;
            slow=tmpnext;
        }
        while(fast && head)
        {
            if(fast->val!=head->val) return false;
            fast=fast->next;
            head=head->next;
        }
        return true;

    }
};

运行效果:
在这里插入图片描述
相同思路使用Python实现的代码如下:

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        if not head:
            return True
        slow=head
        fast=head
        while(fast and fast.next):
            slow=slow.next
            fast=fast.next.next
        tmp=None
        while(slow):
            tmpNext=slow.next
            slow.next=tmp
            tmp=slow
            slow=tmpNext
        fast=head

        while(fast and tmp):
            if(fast.val!=tmp.val):
                return False
            fast=fast.next
            tmp=tmp.next
        return True

运行效果:
在这里插入图片描述

来源:力扣(LeetCode)链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值