【Leetcode】链表题I【python】

【Leetcode】链表题I【python】_第1张图片

class Solution:
    """
    递归思路:不断递归下一个节点
    最后两个节点开始反转
    递归中止条件:当前节点不存在下一个节点
    """
    def reverseList(self, head):
        if not head or not head.next:
            return head
        p = head.next
        n =self.reverseList(p)
        p.next = head
        head.next = None
        return n
    """
    简洁写法,速度快
    swap(a,b)时,不用找中间值
    """
    def reverseList(self, head):
        pre = None
        while head:
            head.next,pre,head = pre,head,head.next
        return pre
    """
    迭代思路:取出当前链表
    然后将其尾插到另一个链表
    """
    def reverstList(self,head):
        pre = None
        while head:
            cur  =  head
            head = head.next
            cur.next = pre
            pre = cur
        return pre

 

你可能感兴趣的:(数据结构与算法)