Merge pull request #720 from bourne-3/bourneLee

143. 重排链表 Java实现补充
This commit is contained in:
程序员Carl
2021-09-08 09:40:52 +08:00
committed by GitHub
2 changed files with 117 additions and 0 deletions

View File

@ -164,6 +164,52 @@ public:
Java Java
```java
class Solution {
List<Integer> path = new ArrayList<>();
int res = 0;
public int sumNumbers(TreeNode root) {
// 如果节点为0那么就返回0
if (root == null) return 0;
// 首先将根节点放到集合中
path.add(root.val);
// 开始递归
recur(root);
return res;
}
public void recur(TreeNode root){
if (root.left == null && root.right == null) {
// 当是叶子节点的时候,开始处理
res += listToInt(path);
return;
}
if (root.left != null){
// 注意有回溯
path.add(root.left.val);
recur(root.left);
path.remove(path.size() - 1);
}
if (root.right != null){
// 注意有回溯
path.add(root.right.val);
recur(root.right);
path.remove(path.size() - 1);
}
return;
}
public int listToInt(List<Integer> path){
int sum = 0;
for (Integer num:path){
// sum * 10 表示进位
sum = sum * 10 + num;
}
return sum;
}
}
```
Python Python
```python3 ```python3
class Solution: class Solution:

View File

@ -177,6 +177,7 @@ public:
Java Java
```java ```java
// 方法三
public class ReorderList { public class ReorderList {
public void reorderList(ListNode head) { public void reorderList(ListNode head) {
ListNode fast = head, slow = head; ListNode fast = head, slow = head;
@ -219,6 +220,76 @@ public class ReorderList {
return headNode.next; 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;
}
}
-------------------------------------------------------------------------
// 方法二:使用双端队列,简化了数组的操作,代码相对于前者更简洁(避免一些边界条件)
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;
}
}
``` ```
Python Python