[LeetCode]24. Swap Nodes in Pairs
来源:互联网 发布:java xp版下载 编辑:程序博客网 时间:2024/04/30 20:59
Given a linked list, swap every two adjacent nodes and return its head.
For example,
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
在处理这种问题时,我们通常加上一个h1头结点指向head,至于思路很清晰了就是隔一个去交换两个相邻结点,比如1->2->3->4->NULL,我们先通过指针交换1和2,再交换3和4,具体的操作流程如下:
曲线上的数字代表每次循环的步骤。
struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {}};class Solution {public:ListNode* swapPairs(ListNode* head) {ListNode *h1 = new ListNode(0);h1->next = head;ListNode *prev = h1, *cur = head;while (cur&&cur->next){prev->next = cur->next; cur->next = cur->next->next; //确定后继新交换的起点,下面有cur=cur->next prev->next->next = cur; prev = cur; cur = cur->next; //当前为新交换的起始点}return h1->next;}};
阅读全文
1 0
- [LeetCode]24.Swap Nodes in Pairs
- 24. Swap Nodes in Pairs Leetcode Python
- LeetCode --- 24. Swap Nodes in Pairs
- LeetCode 24.Swap Nodes in Pairs
- [Leetcode] 24. Swap Nodes in Pairs
- 【LeetCode】24.Swap Nodes in Pairs
- [leetcode] 24.Swap Nodes in Pairs
- **LeetCode 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs LeetCode
- leetcode 24. Swap Nodes in Pairs
- leetcode 24. Swap Nodes in Pairs
- LeetCode--24. Swap Nodes in Pairs
- leetcode 24. Swap Nodes in Pairs
- 【LeetCode】24. Swap Nodes in Pairs
- [leetcode] 24. Swap Nodes in Pairs
- LeetCode 24. Swap Nodes in Pairs
- LeetCode-24.Swap Nodes in Pairs
- LeetCode 24. Swap Nodes in Pairs
- 13.struts2_主题
- 常用汇编指令
- 中国大学慕课C语言第二讲作业
- centos配置samba后,windows无法访问问题
- 分机号-蓝桥杯决赛
- [LeetCode]24. Swap Nodes in Pairs
- Android底部弹出的popupWindow
- 中文分词的条件随机场模型(CRF)介绍
- Git版本控制学习
- 安卓常用框架
- c++第六次实验-静态数据成员时钟
- 洛谷OJ
- netbeans和myeclipse配置tomcat
- SQL Server sp_executesql介绍和使用