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

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

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
全部评论

相关推荐

10-30 10:16
南京大学 Java
龚至诚:给南大✌️跪了
点赞 评论 收藏
分享
10-05 23:02
东北大学 Java
我说句实话啊:那时候看三个月培训班视频,随便做个项目背点八股,都能说3 40w是侮辱价
点赞 评论 收藏
分享
4 收藏 评论
分享
牛客网
牛客企业服务