python 反转链表 LeetCode

反转一个单链表。

示例:

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

代码示例:

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

class Solution(object):
    def reverseList(self, head, pre=None):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        #迭代:循环?
        while head:
            cur = head
            head = head.next
            cur.next = pre
            pre = cur
        return pre

猜你喜欢

转载自blog.csdn.net/shashen12300/article/details/83818611
今日推荐