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

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

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

思路:将链表倒序排序之后再与原始表比较是否相等

正确的实现代码:

class Solution:
    def isPail(self , head: ListNode) -> bool:
        # write code here
        cur = head
        N0 = ListNode(-1)
        while cur:
            temp = N0.next
            N0.next = ListNode(cur.val)
            N0.next.next = temp
            cur = cur.next
        reversehead = N0.next
        while head:
            if head.val != reversehead.val:
                return False
            else:
                head = head.next
                reversehead = reversehead.next
        return True
    
    def reverseListNode(self, head: ListNode) -> ListNode:
        prehead = None
        while head:
            temp = head.next
            head.next = prehead
            prehead = head 
            head = temp
        return prehead

错误代码: 误区:不能在同一链表上做倒排操作

    def isPail(self , head: ListNode) -> bool:
        # write code here
        cur = head 
        reversehead = self.reverseListNode(cur)
        while head:
            if head.val != reversehead.val:
                return False
            else:
                head = head.next
                reversehead = reversehead.next
        return True
    
    def reverseListNode(self, head: ListNode) -> ListNode:
        prehead = None
        while head:
            temp = head.next
            head.next = prehead
            prehead = head 
            head = temp
        return prehead
全部评论

相关推荐

喜欢走神的孤勇者练习时长两年半:池是池,发是发,我曾池,我现黑
点赞 评论 收藏
分享
评论
4
收藏
分享
牛客网
牛客企业服务