问题:
题目来源:力扣(LeetCode)
难度:简单
分析:
使用迭代和递归两种方法实现
解决方法:
1:迭代
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution():
def reverseList(self,head):
pre = None
cur = head
while cur:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
return pre
复杂度:O(n)
2:递归
链表的题目经常靠递归,要想清楚递归的子问题是什么,递归的终止条件是什么
class Solution():
def reverseList(self,head):
#如果列表为空或者列表已经到结尾,返回头结点
def helper(pre,cur):
if cur is None:
return pre
cur_next = cur.next
cur.next = pre
return helper(cur,cur_next)
return helper(None,head)
复杂度:O(n)