题目要求:
Reverse a singly linked list.
# 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")的用法:
- Python利用float("inf")和float("inf")表示正负无穷
- 利用float("inf")做简单加、乘算术运算仍会得到float("inf"):
'>>>1 + float("inf")
inf- '>>>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,所以这么写没毛病。