本文首发于我的个人博客Suixin’s Blog
原文: https://suixinblog.cn/2019/02/target-offer-reverse-linked-list.html 作者: Suixin
题目描述
输入一个链表,反转链表后,输出新链表的表头。
解题思路
只需要一个中间节点过渡一下就好。
代码
Python(2.7.3)
代码中,last
指上一个反转的节点,tmp
指当前节点的后继节点(为了赋值给当前节点完成循环),pHead
为当前节点。
# -*- 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