题目
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.
思路
思路一:遍历交换
本题需要我们对链表进行两两的交换,并且
1.如何交换表头
这里已经用过很多遍了,在链表的表头增加一个辅助节点。
ListNode* result = new ListNode(-1);
result->next = head;
2.如何进行链表的两两交换
链表的交换涉及到三个节点:当前节点(cur),当前节点的下一个节点(first),当前节点的下下个节点(second),交换原理如图1:
![](https://i.loli.net/2019/05/30/5cefa93a03c8c52259.jpg)
![](https://i.loli.net/2019/05/30/5cefb26878b0c63365.jpg)
- 思路一
/**
* 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;
}
};
- 思路二
/**
* 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;
}
};