链表重排序

题目要求:对于链表如L1->L2->L3->L4->L5->L6->L7重新排列为L1->L7->L2->L6->L3->L5->L4

解题1.先将先找到中间节点,将链表从中间节点分为两部分(技巧,只需写两个引用,一个步长为1,一个步长为2,步长为2 的结束时,步长为1 的自然就在中间位置)

2.将后一部分的链表进行倒置

3.合并链表即为所得

def noHeadreverseList(head):

    if head == None or head.next == None:

        return

    cur = head.next

    pre = head

    pre.next = None

    while cur !=None:

        next = cur.next

        cur.next = pre

        pre = cur

        cur = next

    return pre

def findMidder(a):

    if a is None or a.next is None:

        return

    twoStep = a

    oneStep = a

    oneStepPre = a

    while twoStep is not None and twoStep.next is not None:

        oneStepPre = oneStep

        oneStep = oneStep.next

        twoStep = twoStep.next.next

    oneStepPre.next = None

    return oneStep

def reOrder(a):

    if a is None or a.next is None:

        return



    mid = findMidder(a.next)

    cur2 = noHeadreverseList(mid)

    s = cur2

    while s != None:

        print(s.x, end=" ")

        s = s.next

    print()

    cur = a.next

    while cur.next is not None:

        tmp = cur.next

        cur.next = cur2

        cur = tmp

        tmp = cur2.next

        cur2.next = cur

        cur2=tmp

    cur.next = cur2

你可能感兴趣的:(链表重排序)