206. 反转链表
题目描述
反转一个单链表。
原题请参考链接https://leetcode-cn.com/problems/reverse-linked-list/
题解
方法一 【迭代(双指针)】
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
pre = None
cur = head
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
方法二 【递归】
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head == None or head.next == None:
return head
new_head = self.reverseList(head.next)
head.next.next = head
head.next = None
return new_head
python

浙公网安备 33010602011771号