zoukankan      html  css  js  c++  java
  • 142-206. 反转链表

    反转一个单链表。(第一个我写的,其他的你猜)
    class Solution(object):
        def reverseList1(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            new_head = ListNode(-1)
            temp = head  # 记录当前节点
            pre = None   # 记录当前节点的上一个节点
            while temp:
                new_head.next = temp  # 将新节点的next执行temp
                cur = temp  # 记录当前节点
                temp = temp.next  # 记录下一个节点
                cur.next = pre  # 改变当前节点的下一个节点
                pre = cur  # 更新temp的上一个节点
            return new_head.next
    
        def search(self, root):
            """遍历"""
            temp = root
            print(temp.val)
            while temp.next:
                temp = temp.next
                print(temp.val)
    
        def reverseList2(self, head):
            """我一直梦想达到这个水平但是却离得更远
            :type head: ListNode
            :rtype: ListNode
            """
            cur, pre = head, None
            while cur:
                pre ,cur.next, cur = cur, pre, cur.next
            return pre
    
        def reverseList(self, head):
            """类似于reverseList2,但是人家的更灵巧
            :type head: ListNode
            :rtype: ListNode
            """
            pre = None
            cur = head
            while cur:
                tmp = cur.next
                cur.next = pre
    
                pre = cur
                cur = tmp
            return pre
    
    
    if __name__ == '__main__':
        root = ListNode(1)
        n2 = ListNode(2)
        n3 = ListNode(3)
        n4 = ListNode(4)
        n5 = ListNode(5)
    
        n4.next = n5
        n3.next = n4
        n2.next = n3
    
        root.next = n2
    
        s = Solution()
        new_node = s.reverseList(root)
        s.search(new_node)
    
  • 相关阅读:
    [译] 第二十天:Stanford CoreNLP
    [译] 第十九天: Ember
    [译] 第十八天:BoilerPipe
    [译] 第十七天:JBoss Forge
    [译] 第十六天: Goose Extractor
    [译] 第十五天:Meteor
    [译] 第十四天:Standford NER
    [译] 第十三天:Dropwizard
    [译] 第十二天: OpenCV
    hadoop-MR
  • 原文地址:https://www.cnblogs.com/liuzhanghao/p/14281989.html
Copyright © 2011-2022 走看看