标签:ret ini 空间复杂度 none value 额外 list self bsp
要求:如果链表长度为N,时间复杂度为O(N),额外的空间复杂度为O(1)
1 → 2 → 3 → 4 → 5
(1)first = head = 1
循环:
temp = head.next 2
head.next = temp.next 1 → 3
temp.next = first 2 →1
first = temp 2 【此时的头结点是2】
class Node: def __init__(self,value): self.value = value self.next = None def reverseList(head): if not head: return head first = head while head.next: temp = head.next head.next = head.next.next temp.next = first first = temp return first head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) reverseList(head)
只要将每个节点的 next 和 last 互换就可以了。
class Node: def __init__(self,value): self.value = value self.next = None def reverseList(head): if not head: return head #重点 while head: head.next , head.last = head.last,head.next head = head.last return head head = Node(1) head.last = None head.next = Node(2) head.next.last = head head.next.next = Node(3) head.next.next.last = head.next head.next.next.next = Node(4) head.next.next.next.last = head.next.next head.next.next.next.next = Node(5) head.next.next.next.next.last = head.next.next.next reverseList(head)
标签:ret ini 空间复杂度 none value 额外 list self bsp
原文地址:https://www.cnblogs.com/Lee-yl/p/9734407.html