解法1:尾插法
class Solution:
def tailReverse(self,pHead):#尾插法
if not pHead :
return
if not pHead.next:
return pHead
newhead=None
cur=pHead
while cur:
node=Node(cur.data)
if not newhead:
newhead=node
else:
node.next=newhead
newhead=node
cur=cur.next
return newhead
解法2:
class Solution: # 返回ListNode
def ReverseList(self, pHead):
if pHead == None or pHead.next == None:
return pHead
cur = pHead
tmp = None
newhead = None
while cur:
tmp = cur.next
cur.next = newhead
newhead = cur
cur = tmp
return newhead
解法2图解
链表
初始化变量
第一次循环
第二次循环
第三次循环