【LeetCode】206. Reverse Linked List
2015-09-10 16:45
447 查看
题目:
Reverse a singly linked list.提示:
此题不难,可以用迭代或者递归两种方法求解。记得要把原来的链表头的next置为NULL;代码:
迭代:/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { if(!head) return NULL; ListNode *pre = head, *cur = head->next; pre->next = NULL; ListNode *tmp; while (cur) { tmp = cur->next; cur->next = pre; pre = cur; cur = tmp; } return pre; } };
递归:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { return reverseNode(head, NULL); } ListNode* reverseNode(ListNode* head, ListNode* newHead) { if (!head) return newHead; ListNode *next = head->next; head->next = newHead; return reverseNode(next, head); } };
相关文章推荐
- Visual Studio VS2010统计代码行数
- 为Cordova + Ionic + AngularJS 应用添加微信分享功能
- BAE(疑惑)
- HTML-CSS
- 2015多校联合第二场hdu5303Delicious Apples DP 类似最长山峰序列
- 学习Java 23种设计模式详解笔记之行为型模式(三)
- 商户入网第三方支付——支付接口
- 0909我对操作系统的认识
- uva 1513 - Movie collection--树状数组--预留前n个位置
- android 调用相机拍照 伪闪退
- C++ explicit
- 如何截获并替换系统最小化功能
- 个人学习笔记---软中断(下半部)和软件中断(系统调用)的区别
- springmvc checkboxes 回显问题
- 热备,冷备,云备的区别
- SPDY 是什么?如何部署 SPDY?
- 一段代码 完全解读 SharedPreferedces。
- 避免引用Context造成的内存泄露
- 数据结构中的二叉树
- 选择多个或者单个图片显示该图片及属性