思路:递归或者迭代,每次使用三个节点,pre、now、next
即可实现交换,主要对链表头两个节点的交换有特殊性(不能用pre
);
奇怪的是递归和迭代所占空间竟然差不多;
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) {
}
};
// 递归
// ListNode *swapPairs(ListNode *head)
// {
// if (head == nullptr)
// {
// return NULL;
// }
// if (head->next == nullptr)
// {
// return head;
// }
// ListNode *temp = head->next;
// head->next = temp->next;
// temp->next = head;
// fun(head->next, head);
// return temp;
// }
// void fun(ListNode *now, ListNode *pre)
// {
// if (now == nullptr || now->next == nullptr)
// {
// return;
// }
// ListNode *temp = now->next;
// now->next = temp->next;
// temp->next = now;
// pre->next = temp;
// fun(now->next, now);
// }
// 迭代
ListNode *swapPairs(ListNode *head)
{
if (head == nullptr)
{
return NULL;
}
if (head->next == nullptr)
{
return head;
}
bool flag = true; //对链表前两个数进行交换,则不能用pre
ListNode *now = head;
ListNode *res = NULL;
ListNode *pre = NULL;
while (now != nullptr && now->next != nullptr)
{
//实现交换
ListNode *temp = now->next;
now->next = temp->next;
temp->next = now;
if (!flag) //非第一次交换,则需要pre连接到交换后的节点
{
pre->next = temp;
}
else
{
flag = false;
res = temp;
}
pre = now;
now = now->next;
}
return res;
}