一 题目:
二 思路:
1.定义一个虚拟头节点dummyHead和一个搜索指针cur,cur指向虚拟头节点
2.用cur搜索cur->next和cur->next->next,如果不为空就进行交换
三 代码:
#include <bits/stdc++.h>
using namespace std;
typedef struct ListNode{
int val;
struct ListNode *next;
}ListNode;
ListNode *swapList(ListNode *head){
//定义虚拟头结点
ListNode *dummyHead=(ListNode *)malloc(sizeof(ListNode));
dummyHead->next=head;//虚拟头节点指向真正的头节点
ListNode *cur=dummyHead;//定义一个搜索指针
//当要交换的两个节点都不为空时进行交换, 而且cur->next一定要写在前面,因为当cur->next是空指针时cur->next->next会操作空指针使其空指针异常
while(cur->next!=NULL && cur->next->next !=NULL){
ListNode *temp1=cur->next;//记录临时点1
/*注意:
* 这个地方需要注意不用保存节点2,因为在步骤一已经保存了节点2了
*/
ListNode *temp2=cur->next->next->next;//记录临时点3
/*
* 注意这个地方:
* 一开始我想的是可以不用临时变量也可以
* 但是这个想法是错的
* 因为在第一步执行cur->next=cur->next->next;时,cur->next就断了
*/
cur->next=cur->next->next;//步骤一
cur->next->next=temp1;//步骤二
cur->next->next->next=temp2;//步骤三
cur=cur->next->next;//cur移动两位,准备下一轮交换
}
ListNode *res=dummyHead->next;
free(dummyHead);
return res;
}
int main() {
// 手动初始化链表节点
ListNode* head = (ListNode*)malloc(sizeof(ListNode));
head->val = 1;
head->next = (ListNode*)malloc(sizeof(ListNode));
head->next->val = 2;
head->next->next = (ListNode*)malloc(sizeof(ListNode));
head->next->next->val = 3;
head->next->next->next = (ListNode*)malloc(sizeof(ListNode));
head->next->next->next->val = 4;
head->next->next->next->next = nullptr;
ListNode *head1=swapList(head);
for (ListNode* cur = head1; cur != nullptr; cur = cur->next) {
cout << cur->val << (cur->next ? " -> " : " -> null");
}
return 0;
}