翻转链表的三种方式

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

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
            q.next = head.next
            head.next = q

    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)

猜你喜欢

转载自www.cnblogs.com/shengguorui/p/11430376.html
今日推荐