给定一个单链表,我们的任务是成对交换链表中的元素。
示例:
> 输入: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL
> 输出: 2 -> 1 -> 4 -> 3 -> 6 -> 5 -> NULL
>
>
> 输入: 1 -> 2 -> 3 -> 4 -> 5 -> NULL
> 输出: 2 -> 1 -> 4 -> 3 -> 5 -> NULL
目录
- [推荐方法 1] 使用递归 – O(n) 时间和 O(n) 空间
- [推荐方法 2] 使用迭代法 – O(n) 时间和 O(1) 空间
- [推荐方法 3] 通过改变链接 – O(n) 时间和 O(1) 空间
[推荐方法 1] 使用递归 – O(n) 时间和 O(n) 空间
> 我们的基本思路是先交换前两个相邻节点的数据,然后递归地处理下一对节点。在每一次递归调用中,我们将当前节点的数据与它的下一个节点进行交换,直到链表中剩余的节点少于两个为止。
下面是上述方法的实现代码:
C++
CODEBLOCK_b024b37f
C
CODEBLOCK_34268c8b
Java
“
// Java program to pairwise swap elements
// in a given linked list
class Node {
int data;
Node next;
Node(int val) {
data = val;
next = null;
}
}
class GfG {
// Recursive function to swap data of nodes in pairs
static void pairwiseSwap(Node head) {
// Base case: if the list is empty or has
// only one node, no swap
if (head == null || head.next == null) {
return;
}
// Swap the data of the current node with the next node
int temp = head.data;
head.data = head.next.data;
head.next.data = temp;
// Recursion for the next pair
pairwiseSwap(head.next.next);
}
static void printList(Node head) {
Node curr = head;
while (curr != null) {
System.out.