Leetcode#24 Swap Nodes in Pairs
Published:
Link:
https://leetcode.com/problems/swap-nodes-in-pairs/description/
Solution:
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* pre_node = NULL;
ListNode* slow = head;
ListNode* fast = head;
while(fast != NULL && fast->next != NULL) {
fast = fast->next;
/* exchange */
if (pre_node != NULL) {
pre_node->next = fast;
} else {
head = fast;
}
slow->next = fast->next;
fast->next = slow;
pre_node = slow;
/* for next iteration */
fast = slow->next;
slow = slow->next;
}
return head;
}
};