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

Posted on 2018-10-13 12:59  _hqc  阅读(125)  评论(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