#include <iostream>
#include <vector>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
int printflistnode(ListNode *head);
class Solution
{
public:
ListNode *swapPairs(ListNode *head)
{
if (head == nullptr || head->next == nullptr) // 空表或只有单个元素直接返回
return head;
ListNode *anode = head;
ListNode *lastchangebehindnode = new ListNode();
while (anode->next != nullptr)
{
// 交换位置
if (anode == head) // 头节点处理
{
ListNode *thirdnode = new ListNode();
thirdnode = head->next->next;
ListNode *secondnode = new ListNode();
secondnode = head;
head = head->next;
head->next = secondnode;
secondnode->next = thirdnode;
lastchangebehindnode = secondnode;
}
else
{
ListNode *thirdnode = new ListNode();
thirdnode = anode->next->next;
ListNode *secondnode = new ListNode();
secondnode = anode;
ListNode *firstnode = new ListNode();
firstnode = anode->next;
lastchangebehindnode->next = firstnode;
firstnode->next = secondnode;
secondnode->next = thirdnode;
lastchangebehindnode=secondnode;
}
if (anode->next != nullptr) // 往后移动1个位置
{
anode = anode->next;
}
else
{
printflistnode(head);
return head;
}
}
printflistnode(head);
return head;
}
};
int main()
{
// 构建链表
vector<int> vec = {2, 5, 3, 4, 6, 2, 2};
ListNode *head;
if (vec.size() > 0)
{
head = new ListNode(vec[0]);
ListNode *last_node = new ListNode();
for (int i = 1; i < vec.size(); i++)
{
if (i == 1)
{
head->next = new ListNode(vec[i]);
last_node = head->next;
}
else
{
last_node->next = new ListNode(vec[i]);
last_node = last_node->next;
}
}
}
else
head = nullptr;
// printf链表
printflistnode(head);
cout << endl;
Solution a;
a.swapPairs(head);
// printflistnode(head);
delete [] head;
return 0;
}
int printflistnode(ListNode *head)
{
ListNode *next_node = head;
while (next_node != nullptr)
{
cout << next_node->val;
next_node = next_node->next;
}
return 0;
}
leetcode24两两交换链表中的节点(记录)C++
于 2023-06-19 10:43:20 首次发布