/**************************************************************************
*
* 24. [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)
*
* Given a linked list, swap every two adjacent nodes and return its head.
* You must solve the problem without modifying the values in the list's nodes
* (i.e., only nodes themselves may be changed.)
*
* Example:
* Input: head = [1,2,3,4]
* Output: [2,1,4,3]
**************************************************************************/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct ListNode NODE;
///
///
/// Approach 1: raw
NODE *swapPairs(NODE *head){
if (NULL == head || NULL == head->next) return head;
NODE dummy;
dummy.next = head;
NODE *pre = &dummy;
NODE *cur = head;
while (cur && cur->next) {
NODE *next = cur->next;
NODE *nnext=next->next;
next->next = cur;
cur->next = nnext;
pre->next = next;
pre = cur;
cur = nnext;
}
return dummy.next;
}
///
///
/// Approach 2: 优化后
NODE *swapPairs(NODE *head) {
NODE **pp = &head, *a, *b;
while ((a = *pp) && (b = a->next)) { //is it a pair?
a->next = b->next;
b->next = a;
*pp = b;
pp = &(a->next); //moves pp to the next pair
}
return head;
}
///
///
/// Approach 3: 交换值,不符合题目要求
static inline void swap(int *a, int *b) {
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}
NODE *swapPairs(NODE *head){
if (NULL == head || NULL == head->next) return head;
NODE *p =head;
while (p && p->next) {
swap(&p->val, &p->next->val);
p = p->next->next;
}
return head;
}