1. 题目
Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2]
Output: [2,1]
2. 题解
第一种方法为迭代法,一次循环遍历就可以了
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
# new是一个新的空链表
new, old = None, head
# 不断将当前链表移动到空链表上
while old:
# 将当前节点以后的,放入tmp中暂时存放
tmp = old.next
# 当前值的下一节点为新创建的链表
old.next = new
# 新的链表更新
new = old
# 旧的链表更新
old = tmp
return new
第二种方法为递归方法
这里说一下递归算法思想:
- 要明确递归的终止条件是什么:中止条件就是如果当前节点为空,返回空;如果当前节点的next为空,返回该节点
- 子问题是什么:除去当前节点以外,翻转剩余的节点,如果本来的链表是1->2->3->4->5,当前节点为1的情况下,递归得到的解为5->4->3->2
- 最后返回的是新的链表的头节点
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
new_node = self.reverseList(head.next)
head.next.next = head
# 防止出现环
head.next = None
return new_node