1.4鏈表重排序

鏈表重排序

題目描述:

給定鏈表 Lo一>L1一>L2… Ln-1一>Ln,把鏈表從新排序爲 Lo >Ln一>L1一>Ln-1->L2一> Ln-2…。要求:(l)在原來鏈表的基礎上進行排序,即不能申請新的結點;(2)只能修改結點的 next 域,不能修改數據域。node

解題思路:

  1. 找出鏈表的中間節點,分紅先後兩個鏈表(可以使用快慢指針法)
  2. 對後半部分鏈表進行逆序
  3. 按照題目要求合併先後兩個鏈表

    實現方法以下圖:

完整代碼:

class Node:
def __init__(self, data=None, next=None):
    self.data = data
    self.next = next


def print_link(head):
    cur = head.next
    while cur is not None:
        print(cur.data, end=' ')
        cur = cur.next
    print()


# 找出鏈表的中間節點
def findMiddleNode(head):
    if head is None or head.next is None:
        return None
    fast = head
    slow = head
    slowpre = head
    while fast is not None:
        slowpre = slow
        if fast.next is None:
            fast = fast.next
        else:
            fast = fast.next.next
        slow = slow.next
    slowpre.next = None
    return head, slow


# 無頭結點鏈表的逆序
def reverse_link(head):
    pre = head
    cur = head.next
    head.next = None
    while cur.next is not None:
        next = cur.next
        cur.next = pre
        pre = cur
        cur = next
    cur.next = pre
    return cur


# 合併先後兩個鏈表
def merge_link(pre_head, back_head):
    pre = pre_head.next
    cur = back_head
    while pre.next is not None:
        pre_next = pre.next
        cur_next = cur.next
        pre.next = cur
        cur.next = pre_next
        pre = pre_next
        cur = cur_next
    if pre.next is None:
        pre.next = cur
    return pre_head


# 構造帶頭結點的鏈表
def con_link(n):
    head = Node()
    cur = head
    for i in range(1, n + 1):
        node = Node(i)
        cur.next = node
        cur = cur.next
    return head


if __name__ == '__main__':
    head = con_link(6)
    print_link(head)
    pre_head, back_head = findMiddleNode(head)
    back_head = reverse_link(back_head)
    head = merge_link(pre_head, back_head)
    print_link(head)

運行結果:

相關文章
相關標籤/搜索