#include<iostream>
using namespace std;
struct ListNode
{
int val;
ListNode* next;
ListNode(int val) :val(val), next(NULL) {};
};
ListNode* Arr2Chain(int a[], int num)
{
ListNode* head = NULL;
ListNode* add = NULL;
ListNode* tail = NULL;
for (int i = 0; i < num; i++)
{
ListNode* add = new ListNode(a[i]);
if (tail != NULL)
{
tail->next = add;
tail = add;
}
else
{
head = tail = add;
}
}
return head;
}
class Solution
{
public:
ListNode* swapPairs(ListNode* head)
{
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* cur = dummyHead;
while (cur->next != NULL && cur->next->next != NULL)
{
ListNode* temp = cur->next;
ListNode* temp1 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = temp;
cur->next->next->next = temp1;
cur = cur->next->next;
}
return dummyHead->next;
}
void printList(ListNode* cur)
{
while (cur != NULL)
{
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
};
int main() {
int a[] = { 1,2,3,4,5,6,7,8,9,10 };
int num = sizeof(a) / sizeof(a[0]);
cout << "num = " << num << endl;
Solution s2;
ListNode* head2 = Arr2Chain(a, num);
s2.printList(head2);
ListNode* cur = s2.swapPairs(head2);
s2.printList(cur);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)