虚拟头节点法试用与对于头节点情况要特殊考虑的题目,比如该题,具体使用方法在我前面博客中有,请自行查阅,现给出该题目代码。
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* xHead = new ListNode(0);
xHead->next = head;
ListNode* cur = xHead;
while(cur->next != NULL && cur->next->next != NULL)
{
ListNode* nod1 = cur->next;
ListNode* nod2 = nod1->next;
ListNode* Next = nod2->next;
cur->next = nod2;
nod2->next = nod1;
nod1->next = Next;
cur = nod1;
}
ListNode* nowhead = xHead->next;
delete xHead;
return nowhead;
}
};