链接:https://www.nowcoder.com/questionTerminal/75e878df47f24fdc9dc3e400ec6058ca?f=discussion 来源:牛客网 # -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 返回ListNode def ReverseList(self, pHead): # write code here if pHead==None or pHead.next==None: return pHead pre = None cur = pHead while cur!=None: tmp = cur.next cur.next = pre pre = cur cur = tmp return pre
思路2:
将原来所有节点组成一个数组,翻转数组,再将数组中的每个加点连接起来。
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 返回ListNode def ReverseList(self, pHead): # write code here if not pHead: return res = [] while pHead: res.append(pHead) pHead = pHead.next res.reverse() for i in range(0,len(res)): cur = res[i] if i == len(res)-1: cur.next = None else: cur.next = res[i+1] return res[0]
原文:https://www.cnblogs.com/ansang/p/12155122.html