Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
/** * 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) { ListNode* newTail = new ListNode(0); ListNode* newPtr = newTail; ListNode* ptr = head; while(ptr != NULL){ if(ptr->next == NULL){ newPtr->next = ptr; break; } else{ ListNode* tmp = ptr->next->next; newPtr->next = ptr->next; newPtr = newPtr->next; newPtr->next = ptr; newPtr = newPtr->next; newPtr->next = NULL; ptr = tmp; } } return newTail->next; } };
/** * 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) { ListNode* p = head; ListNode* begin = NULL; if(p == NULL) { return NULL; } if(p->next != NULL) { ListNode* t = p; p = p->next; t->next = p->next; p->next = t; if(begin == NULL) { begin = p; } p = p->next; } else { return head; } p->next = swapPairs(p->next); return begin; } };