1、 206反转链表
题目描述:给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
1:递归
分析:若头节点为空即链表是空的,或者head.next指向空,即链表只有一个元素时无需反转,直接返回head
若链表不空,采用递归
可将链表视为反转头一个节点和头节点后的所有节点,头节点后的所有节点采用反转头一个节点和头节点后的所有节点的方法,以此类推,构成递归
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head == None or head.next == None:
return head
p = self.reverseList(head.next)
head.next.next = head
head.next = None
return
2、迭代
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
prev = None
curr = head
while curr is not None:
next