24 - Swap Nodes in Pairs
来源:互联网 发布:java虚拟机怎么安装 编辑:程序博客网 时间:2024/06/05 10:51
不说废话,先贴上代码
#include "stdafx.h"#include <iostream>#include <vector>using namespace std;struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};class Solution_024_SwapNodesinPairs{public:ListNode* swapPairs(ListNode* head) {if (head == nullptr || head->next == nullptr){return head;}ListNode dummy(-1);dummy.next = head;for (ListNode *prev = &dummy, *cur = prev->next, *next = cur->next; next; prev = cur, cur = cur->next, next = cur? cur->next:nullptr){prev->next = next;cur->next = next->next;next->next = cur;}return head->next;}};分析过程:
本体设置了dummy结点,因为有了dummy之后,所有的节点都变成拥有前置节点的节点了。所以就不用担心处理头节点这个特殊情况了。
初始状态:
经过第一轮循环后,
实际上节点的顺序是:已经交换了头两个结点的顺序了
根据for循环的第三个条件
prev = cur, cur = cur->next, next = cur? cur->next:nullptr
以此类推
0 0
- [24]Swap Nodes in Pairs
- 24、Swap Nodes in Pairs
- 24 Swap Nodes in Pairs
- #24 Swap Nodes in Pairs
- 24 Swap Nodes in Pairs
- 24 - Swap Nodes in Pairs
- 24 Swap Nodes in Pairs
- [24]Swap Nodes in Pairs
- [24] Swap Nodes in Pairs
- 【24】Swap Nodes in Pairs
- 24-Swap Nodes In Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes In Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- openOffice的使用
- Marlin固件之二:源代码详解与移植
- 二叉排序树转化为排序的双向链表
- hdu 1159 Common Subsequence
- Java深度历险(八)Java I/O
- 24 - Swap Nodes in Pairs
- HDU 2444 (二分图判定+最大匹配)
- hdu 2566 放大的X
- 架构里没有大写的“I”
- oracle存储过程--在应用程序中访问存储过程程序完整举例
- hdu 5400 Arithmetic Sequence(水题一道)
- UVA 11019 Matrix Matcher
- HDU5390 tree dfs序+线段树分层离线+字典树求异或最大值
- 视音频技术零基础学习笔记(四)及解码程序添加注释