mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
更新143.重排链表 增加Java版
This commit is contained in:
@ -1,4 +1,3 @@
|
||||
|
||||
<p align="center">
|
||||
<a href="https://mp.weixin.qq.com/s/RsdcQ9umo09R6cfnwXZlrQ"><img src="https://img.shields.io/badge/PDF下载-代码随想录-blueviolet" alt=""></a>
|
||||
<a href="https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw"><img src="https://img.shields.io/badge/刷题-微信群-green" alt=""></a>
|
||||
@ -63,6 +62,7 @@ public:
|
||||
## 方法二
|
||||
|
||||
把链表放进双向队列,然后通过双向队列一前一后弹出数据,来构造新的链表。这种方法比操作数组容易一些,不用双指针模拟一前一后了
|
||||
|
||||
```C++
|
||||
class Solution {
|
||||
public:
|
||||
@ -176,6 +176,51 @@ public:
|
||||
|
||||
Java:
|
||||
|
||||
```java
|
||||
public class ReorderList {
|
||||
public void reorderList(ListNode head) {
|
||||
ListNode fast = head, slow = head;
|
||||
//求出中点
|
||||
while (fast.next != null && fast.next.next != null) {
|
||||
slow = slow.next;
|
||||
fast = fast.next.next;
|
||||
}
|
||||
//right就是右半部分 12345 就是45 1234 就是34
|
||||
ListNode right = slow.next;
|
||||
//断开左部分和右部分
|
||||
slow.next = null;
|
||||
//反转右部分 right就是反转后右部分的起点
|
||||
right = reverseList(right);
|
||||
//左部分的起点
|
||||
ListNode left = head;
|
||||
//进行左右部分来回连接
|
||||
//这里左部分的节点个数一定大于等于右部分的节点个数 因此只判断right即可
|
||||
while (right != null) {
|
||||
ListNode curLeft = left.next;
|
||||
left.next = right;
|
||||
left = curLeft;
|
||||
|
||||
ListNode curRight = right.next;
|
||||
right.next = left;
|
||||
right = curRight;
|
||||
}
|
||||
}
|
||||
|
||||
public ListNode reverseList(ListNode head) {
|
||||
ListNode headNode = new ListNode(0);
|
||||
ListNode cur = head;
|
||||
ListNode next = null;
|
||||
while (cur != null) {
|
||||
next = cur.next;
|
||||
cur.next = headNode.next;
|
||||
headNode.next = cur;
|
||||
cur = next;
|
||||
}
|
||||
return headNode.next;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Python:
|
||||
|
||||
Go:
|
||||
@ -183,8 +228,10 @@ Go:
|
||||
JavaScript:
|
||||
|
||||
-----------------------
|
||||
|
||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
|
||||
|
||||
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
|
||||
|
||||
|
Reference in New Issue
Block a user