码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-10-13 13:40:40      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:coder   style   http   name   移动   href   \n   col   question   

题目描述

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

题目地址

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. 反转链表 (链表)

标签:coder   style   http   name   移动   href   \n   col   question   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!