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:
@ -177,6 +177,7 @@ public:
|
||||
Java:
|
||||
|
||||
```java
|
||||
// 方法三
|
||||
public class ReorderList {
|
||||
public void reorderList(ListNode head) {
|
||||
ListNode fast = head, slow = head;
|
||||
@ -259,6 +260,35 @@ public class ReorderList {
|
||||
cur.next = null;
|
||||
}
|
||||
}
|
||||
-------------------------------------------------------------------------
|
||||
// 方法二:使用双端队列,简化了数组的操作,代码相对于前者更简洁(避免一些边界条件)
|
||||
class Solution {
|
||||
public void reorderList(ListNode head) {
|
||||
// 使用双端队列的方法来解决
|
||||
Deque<ListNode> de = new LinkedList<>();
|
||||
// 这里是取head的下一个节点,head不需要再入队了,避免造成重复
|
||||
ListNode cur = head.next;
|
||||
while (cur != null){
|
||||
de.offer(cur);
|
||||
cur = cur.next;
|
||||
}
|
||||
cur = head; // 回到头部
|
||||
|
||||
int count = 0;
|
||||
while (!de.isEmpty()){
|
||||
if (count % 2 == 0){
|
||||
// 偶数,取出队列右边尾部的值
|
||||
cur.next = de.pollLast();
|
||||
}else {
|
||||
// 奇数,取出队列左边头部的值
|
||||
cur.next = de.poll();
|
||||
}
|
||||
cur = cur.next;
|
||||
count++;
|
||||
}
|
||||
cur.next = null;
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user