classListNode: def__init__(self, x): self.val = x self.next = None
classSolution: defreverseList(self, head): ifnot head ornot head.next: return head nl = [] while head.next: nl.append(head) head = head.next nl.append(head) l = len(nl) for x inrange(l): if x == 0: nl[x].next = None continue nl[x].next = nl[x-1] if x == (l - 1): return nl[x]
仔细想想自己又傻逼了,何必要遍历两次呢,在第一遍遍历的同时就能操作了:
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: defreverseList(self, head): ifnot head ornot head.next: return head prev_node = None next_node = head.next while head: next_node = head.next head.next = prev_node prev_node = head head = next_node return prev_node
classSolution: defreverseList(self, head): ifnot head: return head if head.next: ss = Solution() last = ss.reverseList(head.next) head.next.next = head head.next = None return last return head
一开始是用list来打草稿,不过想明白递归之后就大同小异了:
1 2 3 4 5 6 7 8 9
defa(l:list)->list: k=[l[0]]
if l[1:]: b=a(l[1:]) b.extend(k) else: return [l[0]] return b