mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
0024Java版按视频思路实现
This commit is contained in:
@ -155,22 +155,24 @@ class Solution {
|
|||||||
|
|
||||||
```java
|
```java
|
||||||
class Solution {
|
class Solution {
|
||||||
ListNode dumyhead = new ListNode(-1);
|
public ListNode swapPairs(ListNode head) {
|
||||||
dumyhead.next = head; // 设置一个虚拟头结点
|
ListNode dumyhead = new ListNode(-1); // 设置一个虚拟头结点
|
||||||
ListNode cur1 = dumyhead; // 将虚拟头结点指向head,这样方面后面做删除操作
|
dumyhead.next = head; // 将虚拟头结点指向head,这样方面后面做删除操作
|
||||||
|
ListNode cur = dumyhead;
|
||||||
ListNode temp; // 临时节点,保存两个节点后面的节点
|
ListNode temp; // 临时节点,保存两个节点后面的节点
|
||||||
ListNode firstnode; // 临时节点,保存两个节点之中的第一个节点
|
ListNode firstnode; // 临时节点,保存两个节点之中的第一个节点
|
||||||
ListNode secondnode; // 临时节点,保存两个节点之中的第二个节点
|
ListNode secondnode; // 临时节点,保存两个节点之中的第二个节点
|
||||||
while (cur1.next != null && cur1.next.next != null) {
|
while (cur.next != null && cur.next.next != null) {
|
||||||
temp = cur1.next.next.next;
|
temp = cur.next.next.next;
|
||||||
firstnode = cur1.next;
|
firstnode = cur.next;
|
||||||
secondnode = cur1.next.next;
|
secondnode = cur.next.next;
|
||||||
cur1.next = secondnode; // 步骤一
|
cur.next = secondnode; // 步骤一
|
||||||
secondnode.next = firstnode; // 步骤二
|
secondnode.next = firstnode; // 步骤二
|
||||||
firstnode.next = temp; // 步骤三
|
firstnode.next = temp; // 步骤三
|
||||||
cur1 = firstnode; // cur移动,准备下一轮交换
|
cur = firstnode; // cur移动,准备下一轮交换
|
||||||
}
|
}
|
||||||
return dumyhead.next;
|
return dumyhead.next;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -429,4 +431,3 @@ 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>
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user