Leetcode Swap Nodes in Pairs
2016-03-02 09:16
543 查看
递归做法:
非递归做法:
/** * 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||head->next==NULL) return head; ListNode *next = head->next; head->next = swapPairs(next->next); next->next = head; return next; } };
非递归做法:
/** * 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) { ListNode*extra = new ListNode(-1); extra->next = head; ListNode *preP=extra; ListNode *p = head; ListNode *q; while(p!=NULL&&p->next!=NULL){ q=p->next; //开始交换 p->next = q->next; q->next = p; preP->next = q;//交换完毕 preP=p; p=preP->next; } return extra->next; } };
相关文章推荐
- node和ionic组合下载真难寻找
- nodejs express
- LinkedList---Delete Node in the Middle of Singly Linked List
- Win7环境下Sublime Text 3下安装NodeJS插件
- nodejs String
- nodejsPath
- ubuntu如何安装nodejs最新版 本
- nodejs 自动重启服务 supervisor
- 通过inode删除指定文件
- 在Windows上安装Node.js模块的方法
- ## 创建第一个node.js工程 ##
- cesium使用NODEJS搭建环境
- win系统下node.js安装及环境配置.
- nodejs 小技巧——使用 supervisor
- Node.js中JavaScript操作MySQL的常用方法整理
- nodejs简易server环境及简易接口路由 写在一起
- hadoop多次格式胡namenode无法启动datanode
- HADOOP namenode启动失败
- Node.js笔记(二)
- node.js源码安装