leetcode题解之反转链表

11 篇文章 0 订阅
3 篇文章 0 订阅

'''
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    '''
    算法1:迭代算法,使用了3个变量实现反转链表功能
    执行用时 :24 ms, 在所有 python3 提交中击败了99.94%的用户
    内存消耗 :13.8 MB, 在所有 python3 提交中击败了99.62%的用户
    '''
    def reverseList(self, head: ListNode) -> ListNode:
        if head is None or head.next is None:
            return head
        p, q = head, head.next
        while q:
            r = q.next #指向q的后继
            q.next = p #修改q的next指针
            p, q = q, r#p、q均后移一位
        head.next = None
        return p
    
    '''
    算法2:递归算法,使用了2个变量实现反转链表功能
    执行用时 :40 ms, 在所有 python3 提交中击败了88.94%的用户
    内存消耗 :18.4 MB, 在所有 python3 提交中击败了14.62%的用户
    '''
    def reverseList2(self, head: ListNode) -> ListNode:
        if head is None or head.next is None:
            return head
        
        def rev(h):
            if h.next is None:
                return (h, h)
            else:
                p, r = rev(h.next)
                p.next = h
                return (h, r)
        
        p, r = rev(head.next)
        p.next = head
        head.next = None
        return r
    
    '''
    算法3:递归算法,更简明的写法
    执行用时 :40 ms, 在所有 python3 提交中击败了88.04%的用户
    内存消耗 :17.3 MB, 在所有 python3 提交中击败了14.52%的用户
    '''
    def reverseList3(self, head: ListNode) -> ListNode:
        if head is None or head.next is None:
            return head
        else:
            p = self.reverseList3(head.next)
            head.next.next = head
            head.next = None
            return p

a = [2, 4, 3, 5, 8]
p = ha = ListNode(a[0])
for x in a[1:]:
    p.next = ListNode(x)
    p = p.next

p = ha
while p is not None:
    print(p.val, end=' ')
    p = p.next
print()

x = Solution()
hb = x.reverseList3(ha)
p = ha
while p is not None:
    print(p.val, end=' ')
    p = p.next
print()
p = hb
while p is not None:
    print(p.val, end=' ')
    p = p.next
print()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值