LeetCode:反转链表(Python版本)

LeetCode刷题日记

  • 反转链表
    • Python代码

反转链表

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/

反转一个单链表。

示例:

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

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

Python代码

# 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):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        l1 = l2 =head
        tmp =[]
        while l1:
            tmp.insert(0, l1.val)
            l1 = l1.next
        l1 = head
        for _ in tmp:
            l1.val = _
            l1 = l1.next
        return l2

执行用时 : 52 ms, 在Reverse Linked List的Python提交中击败了14.81% 的用户
内存消耗 : 13.5 MB, 在Reverse Linked List的Python提交中击败了48.24% 的用户

借用了额外空间完成了。


迭代方法完成,参考题解:

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

class Solution:
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        prev = None
        curr = head
        while curr :
            tmp = curr.next
            curr.next = prev
            prev = curr
            curr = tmp
        return prev

执行用时 : 56 ms, 在Reverse Linked List的Python提交中击败了10.06% 的用户
内存消耗 : 13.4 MB, 在Reverse Linked List的Python提交中击败了49.72% 的用户


在评论区看到了大神的代码,妙啊

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

class Solution:
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        p, rev = head, None
        while p:
            rev, rev.next, p = p, rev, p.next
        return rev

执行用时 : 52 ms, 在Reverse Linked List的Python提交中击败了14.81% 的用户
内存消耗 : 13.5 MB, 在Reverse Linked List的Python提交中击败了45.99% 的用户

你可能感兴趣的:(Python,链表)