Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
class Solution
{
public:
ListNode *swapPairs(ListNode *head)
{
if(head == NULL || head->next==NULL){return head;}
ListNode *p = head->next;
ListNode *q = head;
while (p && q)
{
int temp = p->val;
p->val = q->val;
q->val = temp;
if (p->next && p->next->next)
{
q = q->next->next;
p = p->next->next;
}
else
{
break;
}
}
return head;
}
};
class Solution
{
public:
ListNode *swapPairs(ListNode *head)
{
if(head == NULL || head->next == NULL){
return head;
}
int temp = head->val;
head->val = head->next->val;
head->next->val = temp;
swapPairs(head->next->next);
return head;
}
};