LeetCode: 012- Reverse Linked List

来源:互联网 发布:vue双向数据绑定面试 编辑:程序博客网 时间:2024/06/04 20:04

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 = Noneclass 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%

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

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

好像还有其它快速方法。。

0 0