Reverse Linked List
![](https://www.5288z.com/wp-content/uploads/2020/05/reverse-linked-list-1.png)
Method 1:
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
pre = None
cur = head
while cur:
nexttmp = cur.next
cur.next = pre
pre = cur
cur = nexttmp
return pre
时间复杂度:O(n)
空间复杂度:O(1)
detail step is below the picture:
![](https://www.5288z.com/wp-content/uploads/2020/05/reverse-linked-list-2.png)
Method 2:
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next: return head
p = self.reverseList(head.next)
head.next.next = head
head.next = None
return p
时间复杂度:O(n)
空间复杂度:O(n)
detail step is below the picture:
![](https://www.5288z.com/wp-content/uploads/2020/05/reverse-linked-list-3.png)