当前位置:网站首页>LeetCode143:重排链表
LeetCode143:重排链表
2022-08-04 21:34:00 【斯沃福德】
题目:
思路:双指针
- 由于链表没有索引,所以使用List先将节点依次装入;
- 根据题目要求的顺序,想到双指针 ! i 为最左, j 为最右,每次用 i 指向 j ,即为题目顺序!
指针 i 和 j 每次同时向中间移动,直到 i > j 则停止;
但是每一轮还需要将 j 指向 i+1,以连接本轮的 j 和下一轮的 i; - 注意:最后以一定要让末尾节点指向 null,否则会成环!
由于每一轮最后 i++, j-- ,所以末尾元素的索引是 i 而不是 j;
class Solution {
public void reorderList(ListNode head) {
ArrayList<ListNode> list=new ArrayList<>();
ListNode curr=head;
// 存
while(curr!=null){
list.add(curr);
curr=curr.next;
}
// 双指针!
int i=0;
int j=list.size()-1;
// 修改
while(i<j){
list.get(i).next=list.get(j);
if(i+1<j){
list.get(j).next=list.get(i+1);
}
i++;
j--;
}
// 最后要将i指针的元素指向null !!! 否则成环!
list.get(i).next=null;
}
}
边栏推荐
猜你喜欢
随机推荐
ES6高级-async的用法
Driving point cloud format changes bring efficiency improvement
硬件开发定制全流程解析
win10 uwp use WinDbg to debug
PCBA方案设计——厨房语音秤芯片方案
In which industries is the PMP certificate useful?
[Teach you to use the serial port idle interrupt of the STM32HAL library]
立即升级!WPS Office 出现 0day 高危安全漏洞:可完全接管系统,官方推出紧急更新
Webmine Webpage Mining Trojan Analysis and Disposal
Spss-系统聚类软件实操
"Jianzhi offer" brush title classification
1.读写点云文件
PRIMAL: Pathfinding via Reinforcement and Imitation Multi-Agent Learning 代码解析
JWT actively checks whether the Token has expired
27. Dimensionality reduction
Zynq Fpga图像处理之AXI接口应用——axi_lite接口使用
Altium Designer 19.1.18 - Protecting Locked Objects
Red team kill-free development practice of simulated confrontation
In action: 10 ways to implement delayed tasks, with code!
Altium Designer 19.1.18 - draw polygons copper hollow out, for the cursor just capture solutions