In a linknode list,we define a = list(),then we add some nodes,if we write a[0].next = a[1], that's fine ,it works, but when we turn to a[1].next = a[0],it time exceed,which confused me a lot.
But finally I solved it. because,if we say a[1].next = a[0]. At the beginning we already have a[0].next = a[1] ,but we wrote a[1].next = a[0],it makes a circle, so time limit exceed.
Solution 1
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head:
return None
a = list()
cur = ListNode(0,head)
while head:
a.append(head)
head = head.next
for i in range(len(a)-1,-1,-1):
if i!=0:
a[i-1].next = None
a[i].next = a[i-1]
else:break
return a[len(a)-1]
Solution 2
Recursion: we can come apart this quesion,for instance, we are now at the point "2",we've already reversed the numbers after "3" ,that is 5->4->3,for next step,we need to make "3".next into "2". so we have 2.next.next = 3.
From a macro point of view,what we want,is just go to the end,make them reverse one by one,so I choose recursion,to achieve my goal.
reverse(head->next) ,until the end ,then traceback,make reversion one by one.