leetcode刷题记录--链表反转

题干:206. 反转链表

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

本题思路:

1->NULL;  2->1->NULL; ……;5->4->3->2->1->NULL

代码(python3):

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if head == None:
            return None
        elif head.next == None:
            return head
        end = None
        head0 = head
        while head != None:
            head0 = head.next
            head.next = end
            end = head
            head = head0
        return end

你可能感兴趣的:(leetcode刷题记录--链表反转)