← 返回博客列表
Bloomberg

Bloomberg 面試題:將帶「向下指標」的多層鏈結串列展開

2025-12-23

題目描述

給定一個多層鏈結串列,每個節點除了 next 指標外,還可能有 down 指標指向下一層鏈表。

目標:把整個結構展開成單層鏈結串列。展開規則是:把每個節點的 down 鏈,插入到該節點與原本 next 之間,並保留相對順序。

範例

展開前:

[1] -> [2] -> [3] -> [8] -> [10]
              |
              v
             [4] -> [5] -> [6]
                          |
                          v
                         [7]

[8] 也有 down:
[8]
 |
 v
[9]

展開後:

[1] -> [2] -> [3] -> [4] -> [5] -> [6] -> [7] -> [8] -> [9] -> [10]

解題思路

常見兩種做法:

Python(遞迴)

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


def flatten(head: Node) -> Node:
    if not head:
        return None

    curr = head
    while curr:
        if curr.down:
            next_node = curr.next
            down_head = flatten(curr.down)
            curr.next = down_head
            curr.down = None

            tail = down_head
            while tail and tail.next:
                tail = tail.next
            if tail:
                tail.next = next_node

        curr = curr.next

    return head

Python(堆疊)

def flatten_iterative(head: Node) -> Node:
    if not head:
        return None

    stack = []
    curr = head

    while curr:
        if curr.down:
            if curr.next:
                stack.append(curr.next)
            curr.next = curr.down
            curr.down = None

        if not curr.next and stack:
            curr.next = stack.pop()

        curr = curr.next

    return head

複雜度


需要面試輔助服務?聯絡 OA VO Service

需要面試真題? 立刻聯繫微信 Coding0201,獲得真題