题目:
第一种解法:非递归:
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
#如果链表为空的情况
if head is None:
return head
#如果链表不为空的情况
pre = None
cur = head
#当链表出现空之后结束循环
while cur:
#先保存下一个值,再反转
temp = cur.next
cur.next=pre
#pre cur 都向后移动
pre = cur
cur=temp
return pre
第二种解法:栈(先入后出)
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
# 创建栈
stack=[]
if head is None:
return head
# 压栈
while head:
stack.append(head.val)
head=head.next
# 先弹出最后一个入栈的值作为头指针
cur=ListNode(stack.pop())
res = cur
# 出栈
while stack:
res.next=ListNode(stack.pop())
res = res.next
return cur