Leetcode 206.反转链表
题目
反转一个单链表。
示例:
输入: 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:
def reverseList(self, head: ListNode) -> ListNode:
res = None
curr = head
while(curr):
temp = curr.next
curr.next = res
res = curr
curr = temp
return res
- 递归法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
res = None
def fuc(head,res):
if(not head):
return res
temp = head.next
head.next = res
res = head
head = temp
return fuc(head,res)
return fuc(head,res)
1859



被折叠的 条评论
为什么被折叠?



