LeetCode题解:Swap Nodes in Pairs
来源:互联网 发布:javascript 清空对象 编辑:程序博客网 时间:2024/05/01 03:07
Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
思路:
一般来说是交换相邻的两个结点的内容就可以解决,无奈题目不允许这么做。只能交换指针了。要注意的是,指向每一对结点中前一个结点的指针也必须更改。
题解:
/** * 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) return nullptr; ListNode* nh = new ListNode(0); nh->next = head; ListNode* h0 = nh; ListNode* h1 = head; ListNode* h2 = head->next; while(h2 != nullptr) { h1->next = h2->next; h2->next = h1; h0->next = h2; h0 = h1; h1 = h1->next; h2 = (h1 ? h1->next : nullptr); } h0 = nh->next; delete nh; return h0; }};
- LeetCode题解:Swap Nodes in Pairs
- leetcode 题解 || Swap Nodes in Pairs 问题
- LeetCode 题解(178): Swap Nodes in Pairs
- LeetCode题解:Swap Nodes in Pairs
- Leetcode题解 24. Swap Nodes in Pairs
- leetcode题解-24. Swap Nodes in Pairs
- [LeetCode]Swap Nodes in Pairs题解
- Leetcode题解-24. Swap Nodes in Pairs
- leetcode题解-24. Swap Nodes in Pairs
- LeetCode题解——Swap Nodes in Pairs
- LeetCode:Swap Nodes in Pairs
- LeetCode: Swap Nodes in Pairs
- [Leetcode] Swap Nodes in Pairs
- LeetCode : Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs
- Leetcode: Swap nodes in pairs
- [LeetCode]Swap Nodes in Pairs
- [LeetCode]Swap Nodes in Pairs
- 谢谢一切改动我生活命运的教师们,谢谢你们!!!
- 敏捷开发方法XP的12个最佳实践
- ios基础教程博客
- BaseAdapter的使用
- SQL Server、Oracle、DB2一决高下
- LeetCode题解:Swap Nodes in Pairs
- replaceAll Dangling meta character '*' near index 0
- 网络语音实时通信音频下的缓冲区设计
- solr包目录
- 工作5年半了,最近准备做一些工作的小结了
- ubuntu下创建备份
- 多线程测试工具groboutils的使用
- 算法导论22.4-2 有向无环图的路径数目
- CCActionEase想说爱你也不难 (上)