Skip to content

Commit

Permalink
0024两两交换链表中的节点 添加Java实现
Browse files Browse the repository at this point in the history
  • Loading branch information
zhenzi committed May 15, 2021
1 parent 9ceecd5 commit 060f1ea
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion problems/0024.两两交换链表中的节点.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,27 @@ public:


Java:

```java
// 虚拟头结点
class Solution {
public ListNode swapPairs(ListNode head) {

ListNode dummyNode = new ListNode(0);
dummyNode.next = head;
ListNode prev = dummyNode;

while (prev.next != null && prev.next.next != null) {
ListNode temp = head.next.next; // 缓存 next
prev.next = head.next; // 将 prev 的 next 改为 head 的 next
head.next.next = head; // 将 head.next(prev.next) 的next,指向 head
head.next = temp; // 将head 的 next 接上缓存的temp
prev = head; // 步进1位
head = head.next; // 步进1位
}
return dummyNode.next;
}
}
```

Python:

Expand Down

0 comments on commit 060f1ea

Please sign in to comment.