剑指offer 15.反转链表
反转链表
http://www.nowcoder.com/questionTerminal/75e878df47f24fdc9dc3e400ec6058ca
15. 反转链表
题目描述
输入一个链表,反转链表后,输出新链表的表头。
思路
使用三个指针,分别指向当前遍历到的结点、它的前一个结点以及后一个结点。当前节点不为空时进行遍历:
当前节点的next = 前一个节点lastNode(进行前后翻转)
前一个节点(lastNode) = 当前节点(往后走一格)
当前节点 = 当前节点的next(往后走一格)
到最后当前节点为空,链表的首节点为lastNode
代码实现
# -*- 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 or not pHead.next:
return pHead
lastNode = None
while pHead:
temp = pHead.next
pHead.next = lastNode
lastNode = pHead
pHead = temp
return lastNode