题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param head ListNode类 # @return ListNode类 #sys.setrecursionlimit(100000) class Solution: def ReverseList(self , head: ListNode) -> ListNode: # write code here #if head is None or head.next is None: #return head ''' newhead = self.ReverseList(head.next) head.next.next = head head.next = None return newhead ''' ''' if not head: return head res = [] while head: res.append(head) head = head.next res = list(reversed(res)) for i in range(len(res) - 1): res[i].next = res[i+1] res[-1].next = None #print(res[0]) return res[0] ''' temp = head res = [] while temp is not None: res.append(temp.val) temp = temp.next res.reverse() temp = head for i in range(len(res)): temp.val = res[i] temp = temp.next return head#python方法就要用python的方法#