lhl
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
  • python

  • leetcode

    • 数组

    • 位运算

    • 动态规划

    • 链表

      • 21. 合并两个有序链表
      • 141. 环形链表
      • 142. 环形链表 II
      • 160. 相交链表
      • 203. 移除链表元素
      • 206. 反转链表
      • 234.回文链表
    • 栈

    • 树

  • 软件测试

  • Git

  • linux

  • 产品

  • MySql

  • docker

  • leetcode
  • list
2023-04-29

反转链表

https://leetcode.cn/problems/reverse-linked-list/ (opens new window)

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:

        pre = None
        cur = head
        while cur:
            next = cur.next
            cur.next = pre
            pre = cur
            cur = next

        return pre
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
    let cur = head
    let pre = null
    while(cur != null){
        const t = cur.next
        cur.next = pre
        pre = cur
        cur = t
    }
    return pre
};
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
//  参考leetcode cn 官网 解答
var reverseList = function(head) {
    if(head == null || head.next == null) return head
    
    let newHead = reverseList(head.next)
    // 前一个节点是有后一个节点的信息, 
     // 然后前一个节点->后一个节点, 转变成,  后一个节点 -> 前一个节点
    head.next.next = head

    // 前一个节点的next 需要变成 null
    head.next = null
    return newHead
};
203. 移除链表元素
234.回文链表

← 203. 移除链表元素 234.回文链表→

最近更新
01
lhl learn notes
02
filter
06-09
03
decorator
06-09
更多文章>
Theme by Vdoing
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式