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

Posted huangqiancun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了剑指Offer 15. 反转链表 (链表)相关的知识,希望对你有一定的参考价值。

题目描述

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

题目地址

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(
反转后:, end =  )
    while result:
        print(result.val, end =  )
        result = result.next

以上是关于剑指Offer 15. 反转链表 (链表)的主要内容,如果未能解决你的问题,请参考以下文章

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

15剑指offer--反转链表

反转链表(剑指offer-15)

[剑指Offer] 15.反转链表

剑指offer---15---反转链表

剑指offer反转链表python