使用一个栈S来存储相邻两个节点即可
/**
* 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) {
stack<ListNode*> s;
if(head==nullptr || head->next == nullptr){
return head;
}
ListNode * p = new ListNode();
ListNode * cur = head;
head = p;
while(cur!=nullptr && cur->next !=nullptr){
s.push(cur);
s.push(cur->next);
cur = cur->next->next;
p->next = s.top();
s.pop();
p = p->next;
p->next = s.top();
s.pop();
p = p->next;
}
if(cur==nullptr){
p->next = nullptr;
}
else if(cur->next == nullptr){
p->next = cur;
}
return head->next;
}
};