反转链表(Python3)
问题提出:反转一个单链表
解决思路:最先想到的是使用栈来存储链表的第一遍遍历的值。再重新遍历链表,遍历的同时弹出栈的元素(弹出的顺序刚好是链表节点值的倒序),为当前节点赋值当前弹出的值。python可以直接使用list结构存储遍历值,读取的时候倒序读取list元素,就相当于栈的原理。
代码如下( ̄▽ ̄):
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: l = [] temp = head while temp!=None: l.append(temp.val) temp = temp.next i = len(l)-1 temp2 = head while i>=0: temp2.val = l[i] i-=1 temp2 = temp2.next return head
时间与空间消耗:
相关推荐
OldBowl 2020-06-16
muhongdi 2020-05-19
aanndd 2020-08-12
nurvnurv 2020-06-07
willluckysmile 2020-05-03
koushr 2020-11-12
范范 2020-10-28
zhaochen00 2020-10-13
Mars的自语 2020-09-27
steeven 2020-09-18
kka 2020-09-14
qiangde 2020-09-13
聚沙成塔积水成渊 2020-08-16
earthhouge 2020-08-15
范范 2020-07-30
bluetears 2020-07-28
mingyunxiaohai 2020-07-19
horizonheart 2020-07-19
liushall 2020-07-18