递归
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
if pHead == None or pHead.next==None:
return pHead
pre = pHead.next
newhead = self.ReverseList(pre)
pHead.next = None
pre.next = pHead
return newhead
迭代
使用头插法。
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
if pHead == None or pHead.next==None:
return pHead
newhead = None
curhead = pHead
while curhead:
tmp = curhead.next
curhead.next = newhead
newhead = curhead
curhead = tmp
return newhead