首页 > 其他 > 详细

剑指Offer 15. 反转链表 (链表)

时间:2018-10-13 13:27:04      阅读:157      评论:0      收藏:0      [点我收藏+]

题目描述

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

题目地址

https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&tqId=11168&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

思路

pHead始终指向要翻转的结点

last指向翻转后的首结点

每反转一个节点,把pHead的下一个节点指向last,last指向pHead成为反转后的首结点,在把pHead向前移动一个结点直至None结束

Python

# -*- coding:utf-8 -*-
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

# 单向链表链表 node1: 1->2->3
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node5 = ListNode(5)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5

class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        if not pHead or not pHead.next:
            return pHead
        last = None
        while pHead:
            temp = pHead.next
            pHead.next = last
            last = pHead
            pHead = temp
        return last


if __name__ == __main__:
    origin = node1
    print(反转前:, end =  )
    while origin:
        print(origin.val, end =  )
        origin = origin.next
    result = Solution().ReverseList(node1)
    print(\n反转后:, end =  )
    while result:
        print(result.val, end =  )
        result = result.next

剑指Offer 15. 反转链表 (链表)

原文:https://www.cnblogs.com/huangqiancun/p/9782581.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!