您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

给定一个链表,将链表中的元素两两交换

2025/11/10 1:28:18发布15次查看
例如,为了解决需要交换链表中存在的成对节点然后打印它的问题
input : 1->2->3->4->5->6->nulloutput : 2->1->4->3->6->5->nullinput : 1->2->3->4->5->nulloutput : 2->1->4->3->5->nullinput : 1->nulloutput : 1->null
有两种方法可以实现时间复杂度为 o(n) 的解决方案,其中 n 是我们提供的链表的大小,所以现在我们将探索这两种方法
迭代方法我们将在此方法中迭代链表元素,并逐对交换它们,直到它们达到 null。
示例#include <bits/stdc++.h>using namespace std;class node { // node of our listpublic: int data; node* next;};void swappairwise(node* head){ node* temp = head; while (temp != null && temp->next != null) { // for pairwise swap we need to have 2 nodes hence we are checking swap(temp->data, temp->next->data); // swapping the data temp = temp->next->next; // going to the next pair }}void push(node** head_ref, int new_data){ // function to push our data in list node* new_node = new node(); // creating new node new_node->data = new_data; new_node->next = (*head_ref); // head is pushed inwards (*head_ref) = new_node; // our new node becomes our head}void printlist(node* node){ // utility function to print the given linked list while (node != null) { cout << node->data << " "; node = node->next; }}int main(){ node* head = null; push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); cout << "linked list before\n"; printlist(head); swappairwise(head); cout << "\nlinked list after\n"; printlist(head); return 0;}
输出linked list before1 2 3 4 5linked list after2 1 4 3 5

我们将在以下方法中使用相同的公式,但我们将通过递归进行迭代。
递归方法在这种方法中,我们通过递归实现相同的逻辑。
示例#include <bits/stdc++.h>using namespace std;class node { // node of our listpublic: int data; node* next;};void swappairwise(struct node* head){ if (head != null && head->next != null) { // same condition as our iterative swap(head->data, head->next->data); // swapping data swappairwise(head->next->next); // moving to the next pair } return; // else return}void push(node** head_ref, int new_data){ // function to push our data in list node* new_node = new node(); // creating new node new_node->data = new_data; new_node->next = (*head_ref); // head is pushed inwards (*head_ref) = new_node; // our new node becomes our head}void printlist(node* node){ // utility function to print the given linked list while (node != null) { cout << node->data << " "; node = node->next; }}int main(){ node* head = null; push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); cout << "linked list before\n"; printlist(head); swappairwise(head); cout << "\nlinked list after\n"; printlist(head); return 0;}
输出linked list before1 2 3 4 5linked list after2 1 4 3 5

上述代码的解释在这种方法中,我们成对地遍历链表。现在,当我们到达一对时,我们交换它们的数据并移动到下一对,这就是我们的程序在两种方法中进行的方式。
结论在本教程中,我们解决了使用递归和迭代成对交换给定链表的元素。我们还学习了该问题的 c++ 程序以及解决该问题的完整方法(普通)。我们可以用其他语言比如c、java、python等语言来编写同样的程序。我们希望本教程对您有所帮助。
以上就是给定一个链表,将链表中的元素两两交换的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product