206. Reverse Linked List
题目
反转一个单链表
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
代码
迭代方法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
prev = None
curr = head
while curr:
headnext = curr.next
curr.next = prev
prev = curr
curr = headnext
return prev
因为要反转,但又要遍历一遍这个单链表,所以把前后都存下来是最重要的,之后反向指引即可。最后return prev,因为curr会是None。时间复杂度上O(n),空间复杂度O(1)。
递归方法(讨论区)
class Solution:
# @param {ListNode} head
# @return {ListNode}
def reverseList(self, head):
return self._reverse(head)
def _reverse(self, node, prev=None):
if not node:
return prev
n = node.next
node.next = prev
return self._reverse(n, node)
分析一下其实和迭代法差不多,都用当前node去判断