题解 | #反转链表#
反转链表
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
#首先判断头节点为空或者单个节点的情况
if pHead is None:
return pHead
if pHead.next is None:
return pHead
#保存三个节点:当前节点,当前节点的前节点,当前节点的下一个节点
#初始化的时候当前节点是头节点,前节点为None,下一个节点为头节点的下一个节点
preNode = None
tempNode = pHead
nextNode = pHead.next
# 当下一个节点为空停止循环
while(nextNode is not None):
# 核心逻辑:保存当前节点的下一个节点,改变当前节点的next为pre节点,将pre节点改为当前节点,将当前节点改成nextNode
nextNode = tempNode.next
tempNode.next = preNode
preNode = tempNode
tempNode = nextNode
return preNode