topic
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4,you should return the list as 2->1->4->3.
Thinking
A thought: traversing exchange
This question we need pairwise exchange on the list, and
1. How to exchange header
here has been used many times, adding a secondary node in the header of the list.
ListNode* result = new ListNode(-1);
result->next = head;
2. How to list every two switching
exchange list involves three nodes: the next node (cur), the current node (first), the current node in the current node (second), an exchange principle in FIG. :
And the switching operation to achieve the following:
first->next = second->next;
cur->next = second;
cur->next->next = first;
3. How to determine whether you can exchange
swap list must be to ensure that
the next node of the current node and the next the next node must exist, thus increasing the judgment conditions.
Thinking two: recursion
You can easily occur, each of the two nodes exchange list, is actually a recursive operation, as shown in FIG 3.
C++
- A thought
/**
* 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) {
if(head == nullptr || nullptr)
return head;
ListNode* result = new ListNode(0);
result->next = head;
ListNode* cur = result;
while(cur->next != nullptr && cur->next->next != nullptr){
ListNode* first = cur->next;
ListNode* second = cur->next->next;
//节点交换
first->next = second->next;
cur->next = second;
cur->next->next = first;
cur = cur->next->next;
}
return result->next;
}
};
- Ideas two
/**
* 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) {
if(head == nullptr || head->next == nullptr)
return head;
ListNode* result = head -> next;
head->next = swapPairs(result->next);
result->next = head;
return result;
}
};