【Leetcode206】 Reverse Linked List
2016-07-15 16:54
225 查看
题目
将单链表逆置分析
可采用递归和迭代两种思想,注意递归指针变换过程。代码
1.迭代/** * 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 || !head->next) return head; ListNode *p=head; ListNode *head_temp=p->next; while(head_temp){ ListNode *tmp=head_temp->next; head_temp->next=p; p=head_temp; head_temp=tmp; } head->next=NULL; return p; } };
2.递归
/** * 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 || !head->next) return head; ListNode *new_head=reverseList(head->next); head->next->next=head; //串联已逆置部分和head head->next=NULL; return new_head; //返回最底层递归得到的head } };
相关文章推荐
- Codeforces Round #362 (Div. 2) C. Lorenzo Von Matterhorn(暴力)
- cuda 安装方法
- oracle数据库客户端无法分发数据库连接
- Tomcat log4j配置
- mysql 5.6 binlog组提交1
- Nginx之Keepalived高可用
- QRCode生成二维码(java)
- VMWare虚拟机转换成KVM
- solr评分机制
- 回文字符串问题
- mybatis循环map的一些技巧
- 开源新闻速递:Linux Mint 发布 17.3 升级包
- jquery学习网站
- Linux【5】
- [No00009E]几种常见的命名规则
- LeetCode Oj 67. Add Binary
- glClipPlane剪裁平面
- android悬浮窗口的实现
- ubuntu进入不了桌面
- 在线文档查看网站地址