我的个人微信公众号:Microstrong
微信公众号ID:MicrostrongAI
微信公众号介绍:Microstrong(小强)同学主要研究机器学习、深度学习、计算机视觉、智能对话系统相关内容,分享在学习过程中的读书笔记!期待您的关注,欢迎一起学习交流进步!
知乎主页:https://www.zhihu.com/people/MicrostrongAI/activities
206. Reverse Linked List
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
解题思路:
(1)迭代解法
迭代法从前往后遍历链表,定义三个指针分别指向相邻的三个结点,反转前两个结点,即让第二个结点指向第一个结点。然后依次往后移动指针,直到第二个结点为空结束,再处理链表头尾即可。
已经AC的代码:
# 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 head is None or head.next is None:
return head
p1 = head
p2 = head.next
p3 = p2.next
while p2:
p3 = p2.next
p2.next = p1
p1 = p2
p2 = p3
head.next = None
head = p1
return head
(2)递归解法
- 基线条件:空链或只有一个结点,直接返回头指针
- 递归条件:递归调用,返回子链表反转后的头指针
已经AC的代码:
# 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 head is None or head.next is None:
return head
# 有两个以上结点
new_head = self.reverseList(head.next) # 反转以第二个结点为头的子链表
# head.next 此时指向子链表的最后一个结点
# 将之前的头结点放入子链尾
head.next.next = head
head.next = None
return new_head