方法一:递归法
#递归法
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head==None or head.next==None:
return head
#反转后的末尾 也就是第一个
cur=self.reverseList(head.next)
head.next.next=head
head.next=None
return cur
方法二:
入栈 出栈
#用栈
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
stack=[]
p=head
while p!=None:
stack.append(p.val)
p=p.next
p=head
while stack:
p.val=stack.pop()
p=p.next
return head
方法三:迭代法
#迭代法 最好理解的一种方法
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
cur=head
pre=None
while cur!=None:
cur_next=cur.next
cur.next=pre
pre=cur
cur=cur_next
return pre