File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change @@ -177,6 +177,7 @@ public:
177
177
Java:
178
178
179
179
``` java
180
+ // 方法三
180
181
public class ReorderList {
181
182
public void reorderList (ListNode head ) {
182
183
ListNode fast = head, slow = head;
@@ -259,6 +260,35 @@ public class ReorderList {
259
260
cur. next = null ;
260
261
}
261
262
}
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
+ }
262
292
263
293
```
264
294
You can’t perform that action at this time.
0 commit comments