您的位置:首页 > 其它

LeetCode: 012- Reverse Linked List

2016-01-07 00:37 330 查看

Reverse Linked List

最基本的链表操作,

学习后插法和前插法

额外的链接

学习手写lstm

http://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%

后插法:将末尾节点移至表头,将原链表的节点按顺序插入到新链表表头后

前插法:按顺序依次扭转每一个节点的方向

好像还有其它快速方法。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: