【打卡】牛客网:BM13 判断一个链表是否为回文结构

很久没写了,连循环中链表要next都忘记了。 

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类 the head
# @return bool布尔型
#
class Solution:
    def isPail(self, head: ListNode) -> bool:
        # write code here
        newHead = ListNode(0)

        p1 = head
        # p2 = newHead

        cnt = 0
        while p1 is not None:
            cnt += 1

            tmp = ListNode(p1.val)
            tmp.next = newHead

            p1 = p1.next
            newHead = tmp  # p2 = p2.next 粗心做错了,因为反转结束后所需要的便是当前节点,不需要记录第一个节点。

        for i in range(cnt // 2 + 1):
            if head.val != newHead.val:
                return False

            head = head.next
            newHead = newHead.next

        return True

评论中采用list数组的方法:

class Solution:
    def isPail(self , head: ListNode) -> bool:
        # write code here
        list1 = []
        while head != None:
            list1.append(head.val)
            head = head.next
        print(list1)
        left = 0
        right = len(list1)-1
        while left < right:
            if list1[left] != list1[right]:
                return False
            left += 1
            right -= 1
        return True

数组的方法中代码最简洁的:

class Solution:
    def isPail(self , head: ListNode) -> bool:
        res = []
        cur = head 
        while cur:
            res.append(cur.val)
            cur = cur.next
        return res == res[::-1]

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值