206. &92 Reverse Linked List

题目要求:

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,所以这么写没毛病。

示意图
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 每于琐碎世事中遇到一些坎坷挫折,情绪低落,思绪凌乱不堪时,便想起那个夏季,那一场殷殷期待,却没有看到的缤纷流星雨。...
    依兰袭香阅读 748评论 5 7
  • 比特币很火;区块链很火;交易更火! 但随着大机构的进场,交易会变得越来越专业化。想要持续获利,还是“佛系玩家”心法...
    成都队长阅读 2,345评论 1 4

友情链接更多精彩内容