成对交换给定链表中的元素

给定一个单链表,我们的任务是成对交换链表中的元素。

示例:

> 输入: 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.

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。如需转载,请注明文章出处豆丁博客和来源网址。https://shluqu.cn/42262.html
点赞
0.00 平均评分 (0% 分数) - 0