翻转链表的三种方法(python实现)

具体方法来自看图理解单链表的反转,以下为该博客中方法的python实现以及测试

方法一:利用三个指针逐个翻转

def func1(head):
    p = head
    q = head.next
    p.next = None
    while q:
        r = q.next
        q.next = p
        p = q
        q = r
    return p 

方法二:尾插法翻转

def func2(head):
    p = head.next
    while p.next:
        q = p.next
        p.next = q.next
        head.next = q
        q.next = p

    p.next = head
    head = head.next
    p.next.next = None
    return head

方法三:递归

def func3(head):
    if head.next == None:
        return head
    new_head = func3(head.next)
    head.next.next = head
    head.next = None
    return new_head

节点定义及测试用例:

#节点定义
class LNode:
    def __init__(self, x):
        self.val = x
        self.next = None

#测试用例
if __name__ == '__main__':
    l1 = LNode(3)
    l1.next = LNode(2)
    l1.next.next = LNode(1)
    l1.next.next.next = LNode(99)
    l = func3(l1)
    print l.val, l.next.val, l.next.next.val, l.next.next.next.val

猜你喜欢

转载自blog.csdn.net/the__apollo/article/details/78769400