Flip the list of three ways

Method a: flip-by using three pointers

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 

Method two: Flip tail interpolation

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

Method three: Recursive

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

Node definitions and test cases:

# Node definition 
class LNode:
     DEF  the __init__ (Self, X): 
        self.val = X 
        self.next = None 

# test 
IF  the __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)

 

Guess you like

Origin www.cnblogs.com/shengguorui/p/11430376.html