美文网首页
单链表反转

单链表反转

作者: 路人乙yh | 来源:发表于2020-06-27 16:57 被阅读0次
    class Node(object):
        def __init__(self, value=None, next=None):
            self.value = value
            self.next = next
    
    def reverse(head):
        if head == None or head.next == None:
            return head
        pre = None
        next = None
        while head != None:
            next = head.next
            head.next = pre
            pre = head
            head = next
        return pre
    
    if __name__ == '__main__':
        l1 = Node(1)
        l1.next = Node(2)
        l1.next.next = Node(3)
        l2 = reverse(l1)
        print(l2.value, l2.next.value, l2.next.next.value)
    

    相关文章

      网友评论

          本文标题:单链表反转

          本文链接:https://www.haomeiwen.com/subject/znlvfktx.html