lintcode: Reverse Linked List
2016-03-10 10:10
387 查看
Reverse a linked list.
For linked list 1->2->3, the reversed linked list is 3->2->1
Reverse it in-place and in one-pass
最先应该想到的是用栈先依次存储起来,然后弹栈。然而空间复杂度不满足要求。
其实,先保存第二个指针的下一个指针,再翻转两个指针之间的指向就可以达到原地翻转的目的。
参考:http://www.thinksaas.cn/group/topic/395495/
For linked list 1->2->3, the reversed linked list is 3->2->1
Reverse it in-place and in one-pass
最先应该想到的是用栈先依次存储起来,然后弹栈。然而空间复杂度不满足要求。
其实,先保存第二个指针的下一个指针,再翻转两个指针之间的指向就可以达到原地翻转的目的。
参考:http://www.thinksaas.cn/group/topic/395495/
/** * Definition of ListNode * * class ListNode { * public: * int val; * ListNode *next; * * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */ class Solution { public: /** * @param head: The first node of linked list. * @return: The new head of reversed linked list. */ ListNode *reverse(ListNode *head) { // write your code here if(head==NULL||head->next==NULL){ return head; } ListNode *p1=head; ListNode *p2=head->next; while(p2){ ListNode *p2next=p2->next; if(p1==head){ p1->next=NULL; } p2->next=p1; p1=p2; p2=p2next; } //return p2; return p1; } };
相关文章推荐
- 静态库与动态库
- 最小/大堆的操作及堆排序
- MySQL 语句级避免重复插入—— Insert Select Not Exist
- servlet/filter/listener/interceptor区别与联系
- Installation error: INSTALL_CANCELED_BY_USER解决方案
- ios开发UI篇-iOS应用数据存储方式(XML属性列表 -plist)e二
- 交大1102
- 链表操作
- 理解JavaScript中的arguments,callee,caller,apply
- HR系统+人脸识别
- 有人向我反馈了一个bug
- c++ (P262—P277) STL
- link-hover-visited-active
- CSS3文本溢出显示省略号
- css HACK
- explain的使用
- mes生产管理的定义
- 缺失值,表整理—tidyr包
- iOS开发动画(Animation)总结
- Intent传值与Bundle传值的区别(源码分析)