/**
* Definition for singly-linked list.
* 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) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* pre = dummyHead;
ListNode* cur = head;
while(cur!=NULL && cur->next!=NULL){
// 两个都不为NULL才会进行交换
ListNode* nxt = cur->next;
ListNode* tmp = nxt->next;
pre->next = nxt;
nxt->next = cur;
cur->next = tmp;
// 指针移动
pre = cur;
cur = cur->next;
}
return dummyHead->next;
}
};
11-17
04-30
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交