地址:https://leetcode-cn.com/problems/swap-nodes-in-pairs/
思路:每次循环记录要交换的两节点和前一个节点,然后做交换即可
Code:
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL) return head;
ListNode *l=head,*r=head->next,*p;
if(r!=NULL){
l->next=r->next;
r->next=l;
head=r;
p=l; l=p->next;
}
while(l!=NULL&&l->next!=NULL){
r=l->next;
p->next=r;
l->next=r->next;
r->next=l;
p=l; l=p->next;
}
return head;
}
};
int main()
{
return 0;
}