题解 | #判断一个链表是否为回文结构#

判断一个链表是否为回文结构

http://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f

这道题的难点在于用O(1)的space.解决方案是将链表的第二部分就地反转,再跟第一部分逐个比较。

# 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 ):
        # write code here
        def reverseList(head):
            prev, curr, nxt = None, head, head
            while curr:
                nxt = curr.next
                curr.next = prev
                prev = curr
                curr = nxt
            return prev
        if not head or not head.next:
            return True
        dummy = ListNode(0)
        dummy.next = head
        slow, fast = dummy, dummy
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        secondHalf = slow.next
        slow.next = None
        reversedSecondHalf = reverseList(secondHalf)
        p1, p2 = head, reversedSecondHalf
        while p2:
            if p1.val != p2.val:
                return False
            p1 = p1.next
            p2 = p2.next
        return True

全部评论

相关推荐

神哥不得了:神哥来啦~1.建议不要包装,很容易问穿2.没日常也能找到暑期3.简历模板换一下,字体和版式看着好难受,而且最好压缩到一页,技术的倒数第2和3重复啦,项目建议换两个高质量的上去,如果时间够的话,八股就把高频top50的题目多巩固几遍,吃透,注意不要找假高频,这样绝对能找到暑期
点赞 评论 收藏
分享
02-23 00:10
湖南大学 C++
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务