# 24. 两两交换链表中的节点

## 示例

输入：head = [1,2,3,4]



输入：head = []



输入：head = [1]



0 <= Node.val <= 100

## java 实现

java
ListNode dummy = new ListNode(0, head);
// 当前移动指针
ListNode current = dummy;

//a->b->c
//b->a->c
while (current.next != null && current.next.next != null) {
ListNode first = current.next;
ListNode second = current.next.next;
// a->c
first.next = second.next;
// b->a
second.next = first;
// []->b
current.next = second;
// 调整位置
current = current.next.next;
}

// 获取结果
return dummy.next;
}


## 效果

Runtime: 0 ms, faster than 100.00% of Java online submissions for Swap Nodes in Pairs.
Memory Usage: 37 MB, less than 71.71% of Java online submissions for Swap Nodes in Pairs.


# 25. K 个一组翻转链表

k 是一个正整数，它的值小于或等于链表的长度。

## 示例

示例 1：

输入：head = [1,2,3,4,5], k = 2



输入：head = [1,2,3,4,5], k = 3



## 提示：

1 <= k <= n <= 5000

0 <= Node.val <= 1000

# V1-基本实现

## 思路

## java 实现

java
public static ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(-1, head), prev = dummy;
while (true) {
// 检查剩余节点是否有k个，不足则返回
ListNode last = prev;
for (int i = 0; i < k; i++) {
last = last.next;
if (last == null) {
return dummy.next;
}
}

// 翻转k个节点
ListNode curr = prev.next, next;
for (int i = 0; i < k - 1; i++) {
next = curr.next;
curr.next = next.next;
next.next = prev.next;
prev.next = next;
}
prev = curr;
}
}


## 性能

Runtime: 0 ms, faster than 100.00% of Java online submissions for Reverse Nodes in k-Group.
Memory Usage: 39.9 MB, less than 28.23% of Java online submissions for Reverse Nodes in k-Group.


# 开源地址

https://github.com/houbb/leetcode

# 参考资料

https://leetcode.cn/problems/reverse-nodes-in-k-group/