- Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
Example
Example 1:
Input: 1->2->3->4->null
Output: 2->1->4->3->null
Example 2:
Input: 5->null
Output: 5->null
Challenge
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
解法1:实打实交换节点
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: a ListNode
* @return: a ListNode
*/
ListNode * swapPairs(ListNode * head) {
ListNode * dummy = new ListNode(0);
dummy->next = head;
head = dummy;
while(head->next && head->next->next) {
ListNode * p1 = head->next;
ListNode * p2 = head->next->next;
head->next = p2;
p1->next = p2->next;
p2->next = p1;
head = p1;
}
return dummy->next;
}
};
二刷:
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: a ListNode
* @return: a ListNode
*/
ListNode* swapPairs(ListNode *head) {
if (!head || !head->next) return head;
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *prev = dummy;
while(head && head->next) {
prev->next = head->next;
head->next = head->next->next;
prev->next->next = head;
prev = head;
head = head->next;
}
return dummy->next;
}
};
二刷:
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *node = head, *prev = dummy;
while (node && node->next) {
ListNode *tmp = node->next;
node->next = tmp->next;
tmp->next = node;
prev->next = tmp;
prev = node;
node = node->next;
}
return dummy->next;
}
};
解法2:投机取巧法,只交换值,节点不动。
class Solution {
public:
/**
* @param head: a ListNode
* @return: a ListNode
*/
ListNode * swapPairs(ListNode * head) {
int count = 1;
ListNode * origHead = head;
while(head && head->next) {
if (count & 0x1) {
swap(head->val, head->next->val);
}
head = head->next;
count++;
}
return origHead;
}
};
解法3:
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: a ListNode
* @return: a ListNode
*/
ListNode* swapPairs(ListNode *head) {
if (!head || !head->next) return head;
ListNode *tmp = swapPairs(head->next->next);
ListNode *res = head->next;
head->next->next = head;
head->next = tmp;
return res;
}
};
简化后可得:
class Solution {
public:
/**
* @param head: a ListNode
* @return: a ListNode
*/
ListNode* swapPairs(ListNode *head) {
if (!head || !head->next) return head;
ListNode *res = head->next;
head->next = swapPairs(head->next->next);
res->next = head;
return res;
}
};