Merge pull request #2487 from Gemaxis/master

Update 0024.两两交换链表中的节点.md
This commit is contained in:
程序员Carl
2024-04-24 10:23:09 +08:00
committed by GitHub

View File

@ -181,6 +181,23 @@ class Solution {
}
```
```java
// 将步骤 2,3 交换顺序,这样不用定义 temp 节点
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0, head);
ListNode cur = dummy;
while (cur.next != null && cur.next.next != null) {
ListNode node1 = cur.next;// 第 1 个节点
ListNode node2 = cur.next.next;// 第 2 个节点
cur.next = node2; // 步骤 1
node1.next = node2.next;// 步骤 3
node2.next = node1;// 步骤 2
cur = cur.next.next;
}
return dummy.next;
}
```
### Python
```python