leetcode 206. Reverse Linked List 反转链表 链表题
leetcode 2020年3月 每日一题打卡
题目:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
2种方法:
- 迭代:时间复杂度O(N),空间复杂度O(1)。
- 递归:时间复杂度O(N),空间复杂度O(N)。
迭代代码:
# 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
"""
if not head:
return None
pre = None
curr = head
while curr:
tempnext = curr.next
curr.next=pre
pre = curr
curr = tempnext
return pre
递归代码:
# 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:
if not head or not head.next:
return head
nextNode = self.reverseList(head.next)
head.next.next = head
head.next = None
return nextNode