[leetcode] 24 Swap Nodes in Pairs(交换链表相邻结点)
来源:互联网 发布:矩阵kvm 编辑:程序博客网 时间:2024/06/06 06:37
(一)迭代法
在处理这种问题时,我们通常加上一个dummy头结点指向head,至于思路很清晰了就是隔一个去交换两个相邻结点,比如1->2->3->4->NULL,我们先通过指针交换1和2,再交换3和4,详细的指针操作可以看下面的图:
class Solution {public: ListNode* swapPairs(ListNode* head) { ListNode *dummy=new ListNode(0); dummy->next=head; ListNode *prev=dummy,*cur=head; while(cur&&cur->next) { prev->next=cur->next; cur->next=cur->next->next; //先确定后继 prev->next->next=cur; prev=cur; cur=cur->next; } return dummy->next; }};(二)递归版本
递归一向是以精巧著称,我们只需处理好最基础的一部分,剩下的递归即可。如果读者不是很理解的话,可以手动模拟一下。
class Solution {public: ListNode *swapPairs(ListNode *head) { if (head == NULL) return NULL; if (head -> next == NULL) return head; ListNode *tmp = head -> next; head -> next = swapPairs(tmp -> next); tmp -> next = head; // 指向下一部分 return tmp; }};
1 0
- [leetcode] 24 Swap Nodes in Pairs(交换链表相邻结点)
- (LeetCode)Swap Nodes in Pairs --- 交换两个相邻的结点
- Swap Nodes in Pairs(交换链表相邻的两个结点)
- Swap Nodes in Pairs 链表交换相邻的节点
- LeetCode OJ 之 Swap Nodes in Pairs (交换成对相邻结点的值)
- Swap Nodes in Pairs 成对交换结点
- Swap Nodes in Pairs:交换链表数组相邻元素的值
- LeetCode 24 Swap Nodes in Pairs(交换序列中的结点)(Linked List)
- [LeetCode]Swap Nodes in Pairs 成对交换
- [LeetCode]Swap Nodes in Pairs 交换节点
- 交换单链表中相邻的两个元素 Swap Nodes in Pairs
- Swap Nodes in Pairs 交换LinkList的相邻节点
- [C++]LeetCode: 109 Swap Nodes in Pairs (交换相邻节点位置)
- LeetCode-24 Swap Nodes in Pairs(链表中按要求交换节点)
- Leetcode刷题记——24. Swap Nodes in Pairs(交换成对结点)
- leetcode_24. Swap Nodes in Pairs 单链表中成对交换结点位置
- LeetCode24 Swap Nodes in Pairs 成对交换链表节点
- LeetCode Swap Nodes in Pairs交换链表中的两个节点
- jQuery UI基础----13jQurey UI Widgets-slider(滑动器
- 杭电acm2566
- POJ 2236 Wireless Network 并查集
- jQuery UI基础----14jQuery UI Widgets-spinner(下拉框
- c++单例模式初探
- [leetcode] 24 Swap Nodes in Pairs(交换链表相邻结点)
- PAT1014 福尔摩斯的约会
- mongodb数据库的备份和恢复
- c++装饰模式
- JDBC数据库连接
- d3.js学习笔记(一)
- System Design 之 Tiny Uri
- [深入理解Java虚拟机]第三章 对象存活判定算法
- CentOS 创建新用户