【LeetCode】206. Reverse Linked List

我的个人微信公众号:Microstrong

微信公众号ID:MicrostrongAI

微信公众号介绍:Microstrong(小强)同学主要研究机器学习、深度学习、计算机视觉、智能对话系统相关内容,分享在学习过程中的读书笔记!期待您的关注,欢迎一起学习交流进步!

知乎主页:https://www.zhihu.com/people/MicrostrongAI/activities

Github:https://github.com/Microstrong0305

个人博客:https://blog.csdn.net/program_developer

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

Reference:

【1】https://zhuanlan.zhihu.com/p/47709205

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值