[剑指Offer]反转链表

链表的基础知识+Python实现四种链表

题目描述

输入一个链表,反转链表后,输出新链表的表头。

解题思路

只需要一个中间节点过渡一下就好。

代码

Python(2.7.3)
代码中,last指上一个反转的节点,tmp指当前节点的后继节点(为了赋值给当前节点完成循环),pHead为当前节点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# -*- 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 or pHead.next is None:
return pHead
else:
last = None
while pHead is not None:
tmp = pHead.next
pHead.next = last
last = pHead
pHead = tmp
return last

运行时间:45ms
占用内存:5856k

参考

https://www.nowcoder.com/profile/689085/codeBookDetail?submissionId=10032913