美文网首页
206. &92 Reverse Linked List

206. &92 Reverse Linked List

作者: Jonddy | 来源:发表于2018-02-21 19:50 被阅读0次
题目要求:

Reverse a singly linked list.

image.png
# Time:   O(1)
# Space:  O(n)
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        new_head = None       #指针作用
        next = None
        
        while head:
            next = head.next
            head.next =new_head
            new_head = head
            head = next

        return new_head

补充知识点:Python关于正负无穷float("inf")的用法:
  1. Python利用float("inf")和float("inf")表示正负无穷
  2. 利用float("inf")做简单加、乘算术运算仍会得到float("inf"):
    '>>>1 + float("inf")
    inf
  3. '>>>dummy, next, head = 1, 2, 3
    '>>>dummy, next, head = head, dummy, next
    '>>>print(dummy, next, head)
    '3 1 2
# Time:   O(1)
# Space:  O(n)
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        dummy = ListNode(float("-inf"))
        while head:
               dummy.next, head.next, head = head, dummy.next, head.next
         return dummy.next

if __name__ == "__main__":
    head = ListNode(1)
    head.next = ListNode(2)
    head.next.next = ListNode(3)
    head.next.next.next = ListNode(4)
    head.next.next.next.next = ListNode(5)
    print(Solution().reverseList(head))

其中:# dummy.next, head.next, head = head, dummy.next, head.next是节点逆序的常用写法!!!
dummy.next 第一次执行的时候为None,所以这么写没毛病。

示意图

相关文章

网友评论

      本文标题:206. &92 Reverse Linked List

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