首页 > 编程学习 > 【leetcode】206. 反转链表

地址:https://leetcode-cn.com/problems/reverse-linked-list/

1、循环法

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:def reverseList(self, head: ListNode) -> ListNode:curr,prev = head,Nonewhile curr:next = curr.nextcurr.next = prevprev = currcurr = nextreturn prev

2、递归法

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:def reverseList(self, head: ListNode) -> ListNode:if head.next is None or head is None:retun head.nextp = self.reverseList(head.next)head.next.next = headhead.next = Noneretun p

本文链接:https://www.ngui.cc/el/3376906.html
Copyright © 2010-2022 ngui.cc 版权所有 |关于我们| 联系方式| 豫B2-20100000