1. 题目
输入一个单链表,反转链表后,输出链表的所有元素。
2. 解法
2.1 循环(迭代)
# 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:
temp = curr.next
curr.next = prev
prev = curr
curr = temp
return prev
2.2 递归
递归三定律:
(1)递归算法必须有个基本结束条件;
(2)递归算法必须改变自己的状态并向基本结束条件演进;
(3)递归算法必须递归地调用自身。
# 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
"""
return self.reverse(head)
def reverse(self, node, prev = None):
if node == None: #基本结束条件
return prev
else: #改变自己的状态,并向基本结束条件演进
n = node.next
node.next = prev
return self.reverse(n,node) #递归的调用自身