逆序反转单链表 Python 版

题目:
给定一个单向链表的头指针,给出其反向链表。
例如,给定[1, 5, 12, 22, 33, 45],返回[45, 33, 22, 12, 5, 1]

代码:

class LinkedListAlgorithms(object):

    def __init__(self):
        pass

    def reverse_linked_list(self, head):  # 将链表逆序反转
        if head == 0:  # 空链表
            return head
        p = head
        length = 1
        while p != 0:
            length += 1
            p = p.next
        if length == 1:
            return head
        p = head
        pre = 0
        while head != 0:
            p = p.next
            head.next = pre
            pre = head
            head = p
        return pre

主要就是指针的修改,以及遍历时前后两个结点的指向。

你可能感兴趣的:(Python,算法)