Chapter 5: Linked List Challenges

Challenge 1: Create a function that prints out the elements of a linked list in reverse order

  • 思路

    • 利用遞迴的方式來建立call stack, 然後最早被呼叫的print會最晚被執行到。

func printInReverse<T>(_ list: LinkedList<T>) {
    printInReverse(list.head)
}

private func printInReverse<T>(_ node: Node<T>?) {
    // 當node = nil, 表示已經到list末端
    guard let node = node else { return }
    // 技巧:利用遞迴呼叫來建立call stack
    printInReverse(node.next)
    // 最早被呼叫的print會最晚被執行
    print(node.value)
}

Challenge 2: Create a function that returns the middle node of a linked list

  • 思路

    • 利用快慢兩個指針

    • 快指針前速度是慢指針兩倍,當快指針到末端時,慢指針剛好指向中間。

Challenge 3: Create a function that reverses a linked list

  • 思路

    • 利用三個指針prv, cur, next,來進行反轉動作。

    • 投結點要獨立出來處理。

Challenge 4: Create a function that takes two sorted linked lists and merges them into a single sorted linked list

  • 思路

    • newHead指向當前兩個list中最小的node

    • tail指針的移動來進行合併list

Challenge 5: Create a function that removes all occurrences of a specific element from a linked list

  • 思路

    • 一樣用兩根指針pre, cur不斷搜尋

    • 當遇到需要刪除的值就是把pre的next跳過cur, 直接指向cur的next

Last updated