题目描述
输入一个链表,反转链表后,输出新链表的表头。
使用语言:python
1:递归方法
# -*- 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 newphead= self.ReverseList(pHead.next) pHead.next.next=pHead pHead.next=None return newphead
非递归方法:
# -*- 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 last= None while(pHead): tmp=pHead.next pHead.next=last last=pHead pHead=tmp return last
偷个懒:图示详解可参考https://blog.csdn.net/FX677588/article/details/72357389。