leetcode刷题记录(13)-中等

本文记录了LeetCode中的五个题目,包括重排链表、二叉树前序遍历、LRU缓存机制、链表插入排序以及排序链表的解题思路。对于链表问题,提出了从中间截断、倒置后半部分的解决方案;二叉树前序遍历则探讨了递归和迭代两种方法;LRU缓存机制通过双向链表和哈希表实现;链表插入排序和排序链表则利用了类似归并排序的策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.重排链表

题目:

给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

思路:先放进数组里,用数组下标去获取节点


/**
 * 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 {void} Do not return anything, modify head in-place instead.
 */
var reorderList = function(head) {
      const list = [];
  while (head) {
    list.push(head);
    head = head.next;
  }
  const pre = new ListNode();
  let node = pre;
  let count = 0;
  while (list.length) {
    if (count % 2) {
      node.next = list.pop();
    } else {
      node.next = list.shift();
    }
    node = node.next;
    count++;
  }
  node.next=null
  return pre.next;
};

可以考虑优化。看新链表的节点顺序,可以从中间截断,分成两个链表,然后后半部分的链表倒置,最后左右链表依次取第一个节点拼接

/**
 * 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 {void} Do not return anything, modify head in-place instead.
 */
var reorderList = function(head) {
  const dummy = new ListNode(0)
  dummy.next = head

  let slow = dummy
  let quick = dummy

  while (quick && quick.next) {
    slow = slow.next
    quick = quick.next
    quick = quick.next
  }

  let right = slow.next
  slow.next = null
  let left = dummy.next

  right = reverseList(right)

  while (left && right) {
    let lNext = lef
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值