博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode----143. Reorder List
阅读量:4112 次
发布时间:2019-05-25

本文共 2223 字,大约阅读时间需要 7 分钟。

链接:

大意:

给定一个链表 L0 -> L1 ->...->Ln,要求对链表进行重新排序,排序后为:L0->Ln->L1->Ln-1->...  例子:

思路:

第一个想到的肯定就是利用栈了。把每个节点依次添加到栈中,最后每次取首(start)尾(end)元素进行连接。具体看代码。

代码:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */class Solution {    public void reorderList(ListNode head) {        if (head == null || head.next == null)            return ;        ArrayList
list = new ArrayList<>(); ListNode h = head; while (h != null) { list.add(h); h = h.next; } h = new ListNode(0); int start = 0, end = list.size() - 1; while (start <= end) { if (start == end) { h.next = list.get(start); h.next.next = null; break; } else { h.next = list.get(start); h.next.next = list.get(end); h.next.next.next = null; h = h.next.next; } start++; end--; } }}

结果:

结论:

效果并不是很理想,有待改进。

改进:

使用快慢指针找到链表的中点,继而只将链表的后半部分存入栈中。 代码:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */class Solution {    public void reorderList(ListNode head) {        if (head == null || head.next == null)            return ;        ArrayList
list = new ArrayList<>(); // 只存储链表后半部分的节点 ListNode slow = head, fast = head, h = new ListNode(0); while (fast.next != null && fast.next.next != null) { fast = fast.next.next; slow = slow.next; } boolean ou = false; // 判断节点个数的奇偶性 if (fast.next != null) ou = true; slow = slow.next; while (slow != null) { list.add(slow); slow = slow.next; } fast = head; int i = list.size() - 1; while (i >= 0) { h.next = fast; ListNode tmp = fast.next; fast.next = list.get(i--); h = fast.next; fast = tmp; } if (ou) h.next = null; else { h.next = fast; fast.next = null; } }}

 

 

转载地址:http://txesi.baihongyu.com/

你可能感兴趣的文章
phpstorm 集成 xdebug 进行调试
查看>>
npm和node升级的正确方式
查看>>
laravel事务
查看>>
springcloud 连续请求 500
查看>>
vue复用新增和编辑表单
查看>>
Ubuntu 16.04 apt-get更换为国内阿里云源
查看>>
laravel部署到宝塔步骤
查看>>
小程序获取access_token
查看>>
navicat远程连接mysql数据库
查看>>
tp5令牌数据无效 解决方法
查看>>
自己的网站与UCenter整合(大致流程)
查看>>
laravel 制作通用的curd 后台操作
查看>>
【小红书2017年笔试】求一个数组中平均数最大的子数组
查看>>
Linux基础系列-定时器与时间管理
查看>>
Linux基础系列-可执行程序的产生过程
查看>>
Linux基础系列-Kernel 初始化宏
查看>>
Linux子系统系列-I2C
查看>>
<iOS>关于自定义description的一点用法
查看>>
Unix 命令,常用到的
查看>>
Linux操作系统文件系统基础知识详解
查看>>