题目来源
题目描述
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
}
};
题目解析
递归
- 从链表的头节点 head 开始递归。
- 每次递归都负责交换一对节点。由 firstNode 和 secondNode 表示要交换的两个节点。
- 下一次递归则是传递的是下一对需要交换的节点。若链表中还有节点,则继续递归。
- 交换了两个节点以后,返回 secondNode,因为它是交换后的新头
- 在所有节点交换完成以后,我们返回交换后的头,实际上是原始链表的第二个节点。
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head == nullptr || head->next == nullptr){
return head;
}
ListNode *first = head;
ListNode *second = head->next;
first->next = swapPairs(second->next);
second->next = first;
return second;
}
};
迭代模拟
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head == nullptr || head->next == nullptr){
return head;
}
ListNode *dummy = new ListNode();
dummy->next = head;
ListNode *pre = dummy;
while (head && head->next){
ListNode *first = head, *second = head->next;
pre->next = second;
first->next = second->next;
second->next = first;
pre = first;
head = first->next;
}
return dummy->next;
}
};
类似题目