mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加java实现143重排链表
This commit is contained in:
@ -219,6 +219,47 @@ public class ReorderList {
|
||||
return headNode.next;
|
||||
}
|
||||
}
|
||||
|
||||
-------------------------------------------------------------------------
|
||||
// 方法一 Java实现,使用数组存储节点
|
||||
class Solution {
|
||||
public void reorderList(ListNode head) {
|
||||
// 双指针的做法
|
||||
ListNode cur = head;
|
||||
// ArrayList底层是数组,可以使用下标随机访问
|
||||
List<ListNode> list = new ArrayList<>();
|
||||
while (cur != null){
|
||||
list.add(cur);
|
||||
cur = cur.next;
|
||||
}
|
||||
cur = head; // 重新回到头部
|
||||
int l = 1, r = list.size() - 1; // 注意左边是从1开始
|
||||
int count = 0;
|
||||
while (l <= r){
|
||||
if (count % 2 == 0){
|
||||
// 偶数
|
||||
cur.next = list.get(r);
|
||||
r--;
|
||||
}else {
|
||||
// 奇数
|
||||
cur.next = list.get(l);
|
||||
l++;
|
||||
}
|
||||
// 每一次指针都需要移动
|
||||
cur = cur.next;
|
||||
count++;
|
||||
}
|
||||
// 当是偶数的话,需要做额外处理
|
||||
if (list.size() % 2== 0){
|
||||
cur.next = list.get(l);
|
||||
cur = cur.next;
|
||||
}
|
||||
|
||||
// 注意结尾要结束一波
|
||||
cur.next = null;
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Python:
|
||||
|
Reference in New Issue
Block a user