leetcode-Swap Nodes in Pairs
2015-11-03 23:10
567 查看
Difficulty:
Medium
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given
Your algorithm should use only constant space. You may
not modify the values in the list, only nodes itself can be changed.
Medium
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 *front=head; ListNode *rear=front->next; while(rear){ swap(front->val,rear->val); if(!(front=rear->next)) break; rear=rear->next->next; } return head; } };
相关文章推荐
- nodejs 入门
- file、inode在应用层和驱动层之间的联系
- LeetCode Populating Next Right Pointers in Each Node (技巧)
- Node JS学习笔记
- NodeJS操作文件相关总结
- LeetCode OJ:Remove Nth Node From End of List(倒序移除List中的元素)
- node.js+mysql把数据显示到前端简单实例
- leetcode-Delete Node in a Linked List
- nodejs
- ubuntu 开发环境配置及安装 nodejs
- ubuntu 开发环境配置及安装 nodejs
- node.js 中createConnection参数说明
- Node开发项目管理工具 Grunt 对比 Gulp
- Node.js入门
- node express
- LeetCode--Delete Node in a Linked List
- [美国VPS]Ramnode测试
- node.js创建并引用模块
- NodeJS 模块开发及发布详解分享
- 如何发布Node模块到NPM社区