LeetCode-206 反转链表

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24502469/article/details/88535539
# 反转一个单链表。
#
# 示例:
# 输入: 1->2->3->4->5->NULL
# 输出: 5->4->3->2->1->NULL
#
# 进阶:
# 你可以迭代或递归地反转链表。你能否用两种方法解决这道题


class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if head == None:
            return head
        i = head
        if i.next == None:
            return head
        j = i.next
        if j.next == None:
            j.next = i
            i.next = None
            return j
        k = j.next
        while k.next != None:
            j.next = i
            i = j
            j = k
            k = k.next
        j.next = i
        k.next = j
        head.next = None
        return k

猜你喜欢

转载自blog.csdn.net/qq_24502469/article/details/88535539