用 C++ 编写程序,用于成对交换链表的节点
pythonserver side programmingprogramming更新于 2026/2/2 8:44:17
假设我们有一个链表。我们必须交换每两个相邻节点(对)并返回其头节点。这里的限制是,我们不能修改节点的值,只能更改节点本身。因此,如果列表类似于 [1,2,3,4],则结果列表将为 [2,1,4,3]。
为了解决这个问题,我们将遵循以下步骤 −
- 如果 head 不存在,则返回 head
- first := head,second := next of head,dummy 是一个值为 -1 的新节点
- next of dummy := first,and prev := dummy
- while second 不为 null
- temp := next of second
- next of first := next of second
- next of second := first
- next of prev := second
- prev := first
- 如果 temp 不为 null,则 first := temp 并且 second := temp 的下一个,否则中断
- 返回 dummy 的下一个
让我们看看下面的实现以便更好地理解 −
示例
#include <bits/stdc++.h>
using namespace std;
class ListNode{
public:
int val;
ListNode *next;
ListNode(int data){
val = data;
next = NULL;
}
};
ListNode *make_list(vector<int> v){
ListNode *head = new ListNode(v[0]);
for(int i = 1; i<v.size(); i++){
ListNode *ptr = head;
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
return head;
}
void print_list(ListNode *head){
ListNode *ptr = head;
cout << "[";
while(ptr->next){
cout << ptr->val << ", ";
ptr = ptr->next;
}
cout << "]" << endl;
}
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(!head)return head;
ListNode* first= head;
ListNode* second = head->next;
ListNode* dummy = new ListNode(-1);
dummy->next = first;
ListNode* prev = dummy;
while(second){
ListNode* temp = second->next;
first->next = second->next;
second->next = first;
prev->next = second;
prev = first;
if(temp){
first = temp;
second = temp ->next;
}
else break;
}
return dummy->next;
}
};
main(){
Solution ob;
vector<int> v = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
ListNode *head = make_list(v);
print_list(ob.swapPairs(head));
}
输入
{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
输出
[2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13,]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

