Skip to content

Commit cd7ef34

Browse files
committed
添加java实现143重排链表方法二添加
1 parent 425593d commit cd7ef34

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

problems/0143.重排链表.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,7 @@ public:
177177
Java:
178178

179179
```java
180+
// 方法三
180181
public class ReorderList {
181182
public void reorderList(ListNode head) {
182183
ListNode fast = head, slow = head;
@@ -259,6 +260,35 @@ public class ReorderList {
259260
cur.next = null;
260261
}
261262
}
263+
-------------------------------------------------------------------------
264+
// 方法二:使用双端队列,简化了数组的操作,代码相对于前者更简洁(避免一些边界条件)
265+
class Solution {
266+
public void reorderList(ListNode head) {
267+
// 使用双端队列的方法来解决
268+
Deque<ListNode> de = new LinkedList<>();
269+
// 这里是取head的下一个节点,head不需要再入队了,避免造成重复
270+
ListNode cur = head.next;
271+
while (cur != null){
272+
de.offer(cur);
273+
cur = cur.next;
274+
}
275+
cur = head; // 回到头部
276+
277+
int count = 0;
278+
while (!de.isEmpty()){
279+
if (count % 2 == 0){
280+
// 偶数,取出队列右边尾部的值
281+
cur.next = de.pollLast();
282+
}else {
283+
// 奇数,取出队列左边头部的值
284+
cur.next = de.poll();
285+
}
286+
cur = cur.next;
287+
count++;
288+
}
289+
cur.next = null;
290+
}
291+
}
262292

263293
```
264294

0 commit comments

Comments
 (0)