加入哑结点
1对空指针没有特殊处理
10min,和原来写的一模一样
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
if pHead==None:return pHead
dead = ListNode(None)
dead.next = pHead
cur = pHead
pre = dead
while(cur!=None):
next=cur.next
cur.next=pre
pre=cur
cur=next
pHead.next=None
return pre
不加入哑结点,代码更简洁,但是不好理解
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
pre=None
cur=None
while pHead!=None:
cur=pHead
pHead=pHead.next
cur.next=pre
pre=cur
return cur
递归的解法,一次通过。8min
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
if pHead==None:return None #特殊情况
if pHead.next==None:return pHead #边界情况
next=pHead.next
res=self.ReverseList(pHead.next)
next.next=pHead
pHead.next=None
return res
网友评论