题解 | #反转链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
# 一般思路
# -*- 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 pre = None cur = pHead nex = None while cur: # nex为当前节点的下一个节点 nex = cur.next # 当前节点的下一个节点为目前的前一个节点 cur.next = pre #===为下次循环做准备 # 前节点更新(当前节点) # 往下进行 # 最后一次:pre为最后一个节点,cur为空,跳出while循环 pre = cur cur = nex return pre;
# 递归
# -*- 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 None if not pHead.next: return pHead headNode = self.ReverseList(pHead.next) pHead.next.next = pHead pHead.next = None return headNode
查看14道真题和解析