zoukankan      html  css  js  c++  java
  • leetcode_206. 反转链表

    反转一个单链表。
    
    示例:
    
    输入: 1->2->3->4->5->NULL
    输出: 5->4->3->2->1->NULL
    进阶:
    你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/reverse-linked-list
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
    
    
    #栈
    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    
    class Solution:
        def reverseList(self, head: ListNode) -> ListNode:
            ls=[]
            while(head):#压栈
                ls.append(head)
                head=head.next
            p1=p2=ListNode(0,None)
            while(ls):
                t=ls.pop()
                p2.next=t
                p2=p2.next
            p2.next=None    
            return p1.next
    
    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        def reverseList(self, head: ListNode) -> ListNode:
            ls=[]
            if not head or not head.next :
                return head
            while(head):
                ls.append(head)
                head=head.next
            p=p1=ls.pop()
            while(ls):
                p.next=ls.pop()
                p=p.next
            p.next=None
            return p1
    
    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    
    class Solution:
        def reverseList(self, head: ListNode) -> ListNode:
            p=None#建立空节点
            while(head):
                t=head.next#当前节点的下一个
                head.next=p#当前节点的next
                p=head#后移
                head=t#后移
            return p
    
    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    
    class Solution:
        def reverseList(self, head: ListNode) -> ListNode:
            #递归
            if not head or not head.next:
                return head
            t=self.reverseList(head.next)
            head.next.next=head
            head.next=None
            return t
    
  • 相关阅读:
    BZOJ 1036:树的统计Count(树链剖分)
    HDU 5950:Recursive sequence(矩阵快速幂)
    POJ 2763:Housewife Wind(树链剖分)
    HDU 2222:Keywords Search(AC自动机模板)
    HDU 3966:Aragorn's Story(树链剖分)
    矩阵乘法
    HDU 4635:Strongly connected(强连通)
    HDU 3078:Network(LCA之tarjan)
    HDU 2767:Proving Equivalences(强连通)
    HDU 1827:Summer Holiday(强连通)
  • 原文地址:https://www.cnblogs.com/hqzxwm/p/14150183.html
Copyright © 2011-2022 走看看