LeetCode31

206.反转链表

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例 1:

复制代码
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

示例 2:

复制代码
输入:head = [1,2]
输出:[2,1]

示例 3:

复制代码
输入:head = []
输出:[]

提示:

  • 链表中节点的数目范围是 [0, 5000]
  • -5000 <= Node.val <= 5000
python 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if head is None:
            return None
        elif head.next is None:
            return head
        else:
            dummy = ListNode()
            p = head
            while p.next is not None:
                p = p.next
            dummy.next = p
            while 1:
                p = head
                while p.next.next is not None:
                    p = p.next
                p.next.next = p
                p.next = None
                if head.next is None:
                    return dummy.next
python 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if head is None:
            return None
        elif head.next is None:
            return head
        else:
            q = None
            p = head
            while p is not None:
                j = p.next
                p.next = q
                q = p
                p = j
            return q

总结

从后往前,不能遍历到最后一个,只能遍历到倒数第二个。

从前往后,需要三个指针,多一个存储下一个节点。

相关推荐
我叫唧唧波10 分钟前
Python+AI 全栈学习笔记
人工智能·python·学习
8Qi823 分钟前
LeetCode 235. 二叉搜索树的最近公共祖先(LCA)
算法·leetcode·二叉树·递归·二叉搜索树·lca·迭代
AAA大运重卡何师傅(专跑国道)43 分钟前
【无标题】
开发语言·c#
bIo7lyA8v43 分钟前
算法稳定性分析中的随机扰动建模的技术8
算法
copyer_xyf1 小时前
Python 异常处理
前端·后端·python
XBodhi.1 小时前
Visual Studio C++ 语法错误: 缺少“;”(在“return”的前面)
开发语言·c++·visual studio
科研online1 小时前
基于多源数据和XGBoost-SHAP分析中国大陆绿地碳汇空间变异影响因素的非线性相关性与尺度差异
算法·学习方法
麻雀飞吧1 小时前
期货多合约策略目标持仓怎么更新才不乱
python·区块链
Cthy_hy1 小时前
拓扑排序超详解:原理 + Kahn 贪心算法
python·算法·贪心算法
LSssT.2 小时前
【01】Python 机器学习
开发语言·python