Leetcode Swap Nodes in Pairs
来源:互联网 发布:windows mobile 编辑:程序博客网 时间:2024/06/03 21:46
由于国庆比较咸鱼,不知不觉中挑的题目都比较水了,这题的主要意思就是将每对相邻的节点相互对调,但是不能只对调它们的值,所以考察的是对链表的基本操作,几乎说不上什么难度,我对它被标为Medium难度表示不是很理解。
我的解决方法是,先判断这个链表是不是只有一个或者两个节点,如果是,那就不需要对调。另外的情况下,就先保存原本第二个节点的指针(因为它最终会成为链表的头),然后开始对相邻节点进行对调,值得注意的是,由于中间部分的节点(比如A->B->C->D中的C和D)在对调之后,它们之前的那个节点(B)需要对next进行重新赋值,所以在每次循环最后有个保存上一节点指针的动作(front = …)。
代码如下
/** * 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 == NULL) return head; if (head->next == NULL) return head; ListNode* result = head->next; ListNode* front = NULL; while (head != NULL) { ListNode* temp = head->next; if (temp != NULL) { head->next = temp->next; temp->next = head; if (front != NULL) { front->next = temp; } } front = head; head = head->next; } return result; }};
阅读全文
0 0
- 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
- 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
- MongoDB基本操作
- 安装JDK9后eclipse无法启动问题
- 二叉树实现先序遍历(迭代版)
- 四. 正则表达式的使用
- GIT本地删除除master以外所有分支
- Leetcode Swap Nodes in Pairs
- linux 下 *.so动态库引入
- Linux并发服务器编程之多线程并发服务器
- 4. 工厂模式
- 关于QT的 常量中有换行符 的问题
- java面试题及答案
- 【Leetcode】252,253 meeting room系列 区间问题
- UVA
- Python之——Eclipse +PyDev开发python,import其他模块时eclipse会报错,运行却没有问题