LeetCode (24)Swap Nodes in Pairs
来源:互联网 发布:全球地名数据库 编辑:程序博客网 时间:2024/05/21 19:15
(24)Swap Nodes in Pairs
题目:将一个链表的每两个相邻链节做交换,输出交换后的链表。
例如:链表为1->2->3->4,那么返回的链表是2->1->4->3。
另外:不能开额外的链表空间。
根据题目直接从前到后扫一遍就可以了,的确是很简单的一道题,但是有几点需要特殊注意,首先就是0长度的链表,然后就是奇数长度和偶数长度的链表,这个时候只要加一个对链节的判断就可以了。
下面是代码:
class Solution {public: ListNode* swapPairs(ListNode* head) { ListNode *p1 = head; if(p1 == NULL){ return head; } ListNode *p2 = head->next; if(p2 == NULL){ return head; } ListNode *p3 = head->next->next; p2->next = p1; p1->next = p3; head = p2; if(p3 == NULL){ return head; } while(true){ ListNode *p0 = p1; p1=p1->next; p2=p1->next; if(p2 == NULL){ return head; } p3 = p2->next; p2->next = p1; p1->next = p3; p0->next = p2; if(p3 == NULL){ return head; } } return head; }};
0 0
- 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
- Leetcode 24 Swap Nodes in Pairs
- Swap Nodes in Pairs - LeetCode 24
- LeetCode 24 - Swap Nodes in Pairs
- leetcode 24 -- Swap Nodes in Pairs
- LeetCode 24:Swap Nodes in Pairs
- leetcode-24Swap Nodes in Pairs
- leetcode 24: Swap Nodes in Pairs
- Leetcode#24 Swap Nodes in Pairs
- LeetCode 24: Swap Nodes in Pairs
- 京东首页
- 如何分析源代码
- 用Srpingmvc 创建RESTful web service
- java io excel导入导出详解
- contains
- LeetCode (24)Swap Nodes in Pairs
- 线性分类器-KNN、多类SVM、Softmax
- 关于adb shell 提示 device not found 的处理
- SQLite二次封装
- 贪心算法基础之聪明的工匠 hunnu OJ 10611 acm,huffman算法思想
- iOS Label大小不变内容可适应变化(字体大小变化)
- interface_cast做什么的?
- 该公众号暂时无法提供服务,请稍后再试
- Linux驱动开发———平台总线设备驱动