用栈进行替换:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == nullptr || head->next == nullptr)
return head;
ListNode* ptr = head;
stack<ListNode*> data;
ListNode* addhead = new ListNode(0);
ListNode* p = addhead;
int num = 0;
while (ptr != nullptr) {
if (num<2) {
data.push(ptr);
ptr = ptr->next;
num++;
}
else {
for (int i = 0; i<2; i++) {
ListNode* temp = data.top();
p->next = temp;
p = temp;
data.pop();
}
num = 0;
}
}
while (!data.empty()) {
ListNode* temp = data.top();
p->next = temp;
p = temp;
data.pop();
}
p->next = nullptr;
return addhead->next;
}
};