[剑指Offer]反转链表

本文首发于我的个人博客Suixin’s Blog
原文: https://suixinblog.cn/2019/02/target-offer-reverse-linked-list.html  作者: Suixin

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

题目描述

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

解题思路

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

代码

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容