LeetCode: 012- Reverse Linked List
2016-01-07 00:37
330 查看
Reverse Linked List
最基本的链表操作,学习后插法和前插法
额外的链接
学习手写lstmhttp://iamtrask.github.io/2015/11/15/anyone-can-code-lstm/
我的解法
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): """ #后插法 :type head: ListNode :rtype: ListNode if head == None: return head new_head = head while new_head != None and new_head.next != None: new_head = new_head.next cur_new, cur_old = new_head.next, head while 1: cur_tmp = cur_old if cur_old == new_head or cur_old == None: break cur_old = cur_old.next cur_tmp.next = cur_new new_head.next = cur_tmp cur_new = cur_tmp return new_head """ #前插法 if head == None: return None cur_next, cur_now, tail= head.next, head, head while cur_next != None: cur_tmp = cur_next cur_next = cur_next.next cur_tmp.next = cur_now cur_now = cur_tmp tail.next = None return cur_now
确实是最基本的操作, 为了写清晰,速度确实慢了。
后插法:8%
前插法:33%
后插法:将末尾节点移至表头,将原链表的节点按顺序插入到新链表表头后
前插法:按顺序依次扭转每一个节点的方向
好像还有其它快速方法。。
相关文章推荐
- 5种类型的程序员
- Unity中消息事件的封装与运用
- Web服务启动时自动加载Servlet
- inline函数与普通函数的区别
- 13Java语法回顾之filewriter&&filereader
- 保证数据的完整性
- 笔记
- 小猪的Android入门之路 Day 9 part 1
- [Android Studio]For MAC快捷键及功能记录(持续更新)
- [探测与扫描]仿生学-鹰眼的威力
- 小猪的Android入门之路 Day 8 part 6
- 升级Xcode7之后VVDocumenter-Xcode等插件无法使用的解决办法
- 小猪的Android入门之路 Day 8 part 5
- 【C语言提高37】结构体做函数参数进阶
- 中国教育模式的颠覆者--兄弟会
- UVA-1515 Pool construction (最小割)
- JS,Jquery获取各种屏幕的宽度和高度
- 表与数据完整性
- 那些年我们一起做过的shell面试题(一)
- 野生程序员的故事