当前位置: 首页 > news >正文

LCR 026

题目:LCR 026


解法一:线性表

将链表中所有元素加入数组中,创建两个指针,分别指向数组的头部和尾部,然后向中间遍历

    public void reorderList(ListNode head) {if (head == null || head.next == null || head.next.next == null) return;List<ListNode> list = new ArrayList<>();ListNode cur = head;while (cur != null) {list.add(cur);cur = cur.next;}ListNode reorderNode = new ListNode(0, head);for (int i = 0; i < list.size(); i++) {int index1 = i, index2 = list.size() - 1 - i;ListNode start = list.get(index1);ListNode end = list.get(index2);if (index1 == index2) {reorderNode.next = start;start.next = null;break;} else if (index1 == index2 - 1) {reorderNode.next = start;start.next = end;end.next = null;break;} else {reorderNode.next = start;start.next = end;reorderNode = end;}}}

解法二:寻找链表中点 + 链表逆序 + 合并链表

    public void reorderList(ListNode head) {if (head == null || head.next == null || head.next.next == null) return;ListNode middleNode = middleNode(head);ListNode reversedList = reverseList(middleNode);mergeList(head, reversedList);}public ListNode mergeList(ListNode head1, ListNode head2) {if (head1 == null || head2 == null) return head1;ListNode dummy = new ListNode(0), prev = dummy, node1 = head1, node2 = head2;while (node2 != null) {if (node1 == node2) {prev.next = node2;break;}ListNode nextNode1 = node1.next;ListNode nextNode2 = node2.next;prev.next = node1;node1.next = node2;prev = node2;node1 = nextNode1;node2 = nextNode2;}return dummy.next;}public ListNode middleNode(ListNode head) {if (head == null || head.next == null) return head;ListNode slow = head, fast = head;while (fast != null && fast.next != null) {slow = slow.next;fast = fast.next.next;}return slow;}public ListNode reverseList(ListNode head) {ListNode prev = null, cur = head, next;while (cur != null) {next = cur.next;cur.next = prev;prev = cur;cur = next;}return prev;}

http://www.lryc.cn/news/440876.html

相关文章:

  • 万能小程序运营管理系统 _requestPost 任意文件读取漏洞复现
  • libyuv之linux编译
  • vue3路由基本使用
  • 哪些人适合学习人工智能?
  • 计算机的错误计算(九十七)
  • Flask-Migrate的使用
  • python怎么输入整数
  • 代码随想录打卡Day36
  • 速盾:凡科建站开cdn了吗?
  • python贪吃蛇游戏项目源码【免费】
  • Mycat搭建分库分表
  • Python中的数据结构
  • mysql笔记8(多表查询)
  • typescript-tsconfig文件解释
  • 所有用贪心的算法和所有用动态规划(dp)的算法合集
  • 论文阅读 | 基于流模型和可逆噪声层的鲁棒水印框架(AAAI 2023)
  • 上线跨境电商商城的步骤
  • Python基础(七)——PyEcharts数据分析(面向对象版)
  • 滚雪球学SpringCloud[5.1讲]: Spring Cloud Config详解
  • Unity常用随机数算法
  • dial unix /var/run/docker.sock: connect: permission denied
  • Prompt提示词技巧
  • 滑动窗口(6)_找到字符串中所有字母异位词
  • 【无标题】rocket
  • Maven国内镜像(四种)
  • Linux环境中如何快速修改 JAR 包中的配置文件
  • java高频面试题(2024最新)
  • WEB 编程:使用富文本编辑器 Quill 配合 WebBroker 后端
  • 新书出版,大陆首本NestJS图书《NestJS全栈开发解析:快速上手与实践》
  • 面试题:react、vue中的key有什么作用?(key的内部原理)