反转单链列表。
Input:1->2->3->4->5->NULL
Output:5->4->3->2->1->NULL
Method 1 循环 Iterative
遍历链表,cur存储需要处理的节点, pre表示已经转换过的节点, iterative 2.0里面不需要temp
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
pre=None
cur=head
while cur:
temp=cur.next
cur.next=pre
pre=cur
cur=temp
return pre
'''ITERATIVE 2.0
pre,cur=None,head
while cur:
cur.next,pre,cur=pre,cur,cur.next
return pre
'''
'''Input:[1-2-3-4-5]
TEMP: ListNode{val: 2, next: ListNode{val: 3, next: ListNode{val: 4, next: ListNode{val: 5, next: None}}}}
CUR: ListNode{val: 2, next: ListNode{val: 3, next: ListNode{val: 4, next: ListNode{val: 5, next: None}}}}
PRE: ListNode{val: 1, next: None}
TEMP: ListNode{val: 3, next: ListNode{val: 4, next: ListNode{val: 5, next: None}}}
CUR: ListNode{val: 3, next: ListNode{val: 4, next: ListNode{val: 5, next: None}}}
PRE: ListNode{val: 2, next: ListNode{val: 1, next: None}}
TEMP: ListNode{val: 4, next: ListNode{val: 5, next: None}}
CUR: ListNode{val: 4, next: ListNode{val: 5, next: None}}
PRE: ListNode{val: 3, next: ListNode{val: 2, next: ListNode{val: 1, next: None}}}
TEMP: ListNode{val: 5, next: None}
CUR: ListNode{val: 5, next: None}
PRE: ListNode{val: 4, next: ListNode{val: 3, next: ListNode{val: 2, next: ListNode{val: 1, next: None}}}}
TEMP: None
CUR: None
PRE: ListNode{val: 5, next: ListNode{val: 4, next: ListNode{val: 3, next: ListNode{val: 2, next: ListNode{val: 1, next: None}}}}}
'''
时间复杂度O(n)因为有n个数, 空间占用O(1)
Method 2 迭代 Recursive
以1>2>3>4>5为例,当节点4到5已经反转然后下一次要处理3[1>2>3(k)>4(k+1)<5], 第k+1个节点应该指向k, 所以k.next.next=k
当遍历到最后时, 1会指向∅, 所以要判断k和k.next是否为空。
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
res = self.reverseList(head.next)
head.next.next = head
head.next = None
return res
时间复杂度和空间占用都为O(n)