利用递归思想,对n节点交换节点对,显然可以看成,(从head指针开始)先交换头部2个node,在递归交换n-2,并merge(即将交换好的前两个中后一个next指向n-2
公式类似T(n)=O(n^0)+T(n-2);
递归算法分两部分,第一部分递归的最小问题解,类似数学归纳法中n=1的情况;
第二部分递归表达式建立
/**
* 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==NULL||head->next==NULL)
return head;//最小解//假设已知swapPairs(head->next->next);
ListNode *temp=head->next;
ListNode *nextChain=swapPairs(head->next->next);
head->next=nextChain;
temp->next=head;
return temp;
}
};
没有递归
/**
* 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==NULL||head->next==NULL)
return head;
ListNode *real_head=head->next;
ListNode * tw=head->next;
head->next=head->next->next;
tw->next=head;
ListNode *tail=head;
head=tw->next->next;
while(head!=NULL&&head->next!=NULL)
{
tw=head->next;
head->next=head->next->next;
tw->next=head;
tail->next=tw;
tail=head;
head=tw->next->next;
}
return real_head;
}};
精简版
链表节点对交换算法
本文探讨了利用递归及非递归方式实现链表中节点对的交换算法。通过详细解析递归算法的建立与最小问题解,以及非递归方法的迭代过程,为读者提供了深入理解链表操作的视角。
1025

被折叠的 条评论
为什么被折叠?



