一、题目描述
二、思路
- 使用虚拟头节点( phead ),便于题目最后输出头节点;
- 设置三个指针,一个( cur )指向要调换次序的两个节点的上一个节点,另两个( left 、 right )分别指向需要调换次序的节点;
- 当cur的下两个节点都存在时( cur -> next && cur -> next -> next ),进入两两交换节点的循环。
三、解题过程
-
设置虚拟头节点与cur节点
struct ListNode* pHead = (struct ListNode*)malloc(sizeof(struct ListNode));
phead -> next = head;
struct ListNode* cur = pHead;
-
判断是否进入两两交换节点的循环
- 当cur的下两个节点都存在时( cur -> next && cur -> next -> next ),进入循环;
- 先定义left和right(left = cur -> next; right = left -> next),接着将cur的next指针指向right(cur -> next = right),然后将cur往后移一位(cur = left),即成为进入下次循环的俩需要交换的节点的前一个节点,接着将left的next指针指向right的next指针指向的元素(left -> next = right -> next),最后将right的next指针指向left(right -> next = left)。
图解:
while(cur -> next && cur -> next ->next){
struct ListNode* left = cur -> next;
struct ListNode* right = left -> next;
cur -> next = right;
cur = left;
left -> next = right -> next;
right -> next = left;
}
-
输出头节点
return pHead -> next;
四、总代码
struct ListNode* swapPairs(struct ListNode* head){
struct ListNode* pHead = (struct ListNode*)malloc(sizeof(struct ListNode));
pHead -> next = head;
while(cur -> next && cur -> next ->next){
struct ListNode* left = cur -> next;
struct ListNode* right = left -> next;
cur -> next = right;
cur = left;
left -> next = right -> next;
right -> next = left;
}
return pHead -> next;
}
时间复杂度:O(n),空间复杂度:O(1)。