mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 07:35:35 +08:00
Merge pull request #1808 from 812559558/master
更新了问题0024,Java版按B站视频思路实现
This commit is contained in:
@ -154,23 +154,24 @@ class Solution {
|
||||
```
|
||||
|
||||
```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位
|
||||
ListNode dumyhead = new ListNode(-1); // 设置一个虚拟头结点
|
||||
dumyhead.next = head; // 将虚拟头结点指向head,这样方面后面做删除操作
|
||||
ListNode cur = dumyhead;
|
||||
ListNode temp; // 临时节点,保存两个节点后面的节点
|
||||
ListNode firstnode; // 临时节点,保存两个节点之中的第一个节点
|
||||
ListNode secondnode; // 临时节点,保存两个节点之中的第二个节点
|
||||
while (cur.next != null && cur.next.next != null) {
|
||||
temp = cur.next.next.next;
|
||||
firstnode = cur.next;
|
||||
secondnode = cur.next.next;
|
||||
cur.next = secondnode; // 步骤一
|
||||
secondnode.next = firstnode; // 步骤二
|
||||
firstnode.next = temp; // 步骤三
|
||||
cur = firstnode; // cur移动,准备下一轮交换
|
||||
}
|
||||
return dummyNode.next;
|
||||
return dumyhead.next;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
Reference in New Issue
Block a user