LeetCode 24:Swap Nodes in Pairs
2015-11-25 23:54
483 查看
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.
更简洁的方法,但是题目规定了不能这样做:
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.
#include<iostream> #include<algorithm> using namespace std; struct ListNode{ int val; ListNode *next; ListNode(int x) : val(x), next(NULL){ } }; //这道题目考察一个对于单链表轮换的问题,只要弄清楚指针指向对象的顺序问题,然后调用递归就可以解决问题了。 //注意点: //1.链表问题一定要考虑head指向的是一个空链表,即NULL,必须先加以判断,同样这是递归的终止条件。 //2.考虑到链表的元素的奇、偶性,如果最后只剩一个元素,也是终止递归,返回这个元素的值。 class Solution{ public: ListNode* swapPairs(ListNode* head){ if (head == NULL) return NULL; if (head->next == NULL) return head; ListNode* temp = head->next; head->next = swapPairs(temp->next); temp->next = head; return temp; } };
更简洁的方法,但是题目规定了不能这样做:
class Solution{ public: ListNode* swapPairs(ListNode* head){ ListNode* p = head; while (p&&p->next){ swap(p->val, p->next->val); p = p->next->next; } return head; } };
相关文章推荐
- leetcode Swap Nodes in Pairs python
- NodeJs通过async/await处理异步
- 异步式I/O与事件驱动--起步
- NodeJS中使用 eventproxy 控制并发-@JacksonTian
- NodeJS 安装
- node js开发过程中报错整理
- 使用ZooKeeper ACL特性进行znode控制
- 关于cordova/nodejs/npm的坑
- ORM DB for nodejs--sequelize
- mac上连接校园网inode,找不到en3网卡
- 理解inode
- Node.js 菜鸟教程学习
- ROS进阶学习手记 10 - 搭建自己的TurtleBot(4)- Nodes of Base Driver
- leetcode之Delete Node in a Linked List
- node.js开发小项目的全过程 1 快速创建项目
- 222. Count Complete Tree Nodes
- 在node.js中使用mongose模块
- [nodejs入门]第一篇,javascript基础(1)
- WRTnode自启动脚本程序
- nodejs取参四种方法req.body,req.params,req.param,req.body