问题:翻转单链接列表
解决方案:首先考虑的是使用堆栈存储链表中第一个路径的值。 重新遍历链表,在遍历时弹出堆栈的元素,并将当前弹出的值替换为当前节点。 弹出顺序与链表中节点值的顺序相反。 python可以直接使用list结构存储遍历值,读取时按相反顺序读取list元素相当于堆栈的原理。
代码如下(() )。
# definitionforsingly -链接列表。
# class ListNode:
# def __init__(self,x ) :
# self.val=x
# self.next=None
类解决方案:
defreverselist(self,head: ListNode )- ListNode:
l=[]
temp=head
while temp!=None:
L.append(temp.val ) )。
temp=temp.next
I=Len(L )-1
temp2=头
while i=0:
temp2.val=l[i]
i-=1
temp2=temp2.next
返回头
时间和空间消耗: