Java版本按照视频的思路实现

This commit is contained in:
huhaonan
2022-12-08 09:58:53 +08:00
parent 35e8717ee6
commit 50632bc383

View File

@ -154,24 +154,23 @@ class Solution {
``` ```
```java ```java
// 虚拟头结点
class Solution { class Solution {
public ListNode swapPairs(ListNode head) { ListNode dumyhead = new ListNode(-1);
dumyhead.next = head; // 设置一个虚拟头结点
ListNode dummyNode = new ListNode(0); ListNode cur1 = dumyhead; // 将虚拟头结点指向head这样方面后面做删除操作
dummyNode.next = head; ListNode temp; // 临时节点,保存两个节点后面的节点
ListNode prev = dummyNode; ListNode firstnode; // 临时节点,保存两个节点之中的第一个节点
ListNode secondnode; // 临时节点,保存两个节点之中的第二个节点
while (prev.next != null && prev.next.next != null) { while (cur1.next != null && cur1.next.next != null) {
ListNode temp = head.next.next; // 缓存 next temp = cur1.next.next.next;
prev.next = head.next; // 将 prev 的 next 改为 head 的 next firstnode = cur1.next;
head.next.next = head; // 将 head.next(prev.next) 的next指向 head secondnode = cur1.next.next;
head.next = temp; // 将head 的 next 接上缓存的temp cur1.next = secondnode; // 步骤一
prev = head; // 步进1位 secondnode.next = firstnode; // 步骤二
head = head.next; // 步进1位 firstnode.next = temp; // 步骤三
} cur1 = firstnode; // cur移动准备下一轮交换
return dummyNode.next;
} }
return dumyhead.next;
} }
``` ```
@ -430,3 +429,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank"> <a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/> <img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a> </a>