Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
OrganizationAdvent CalendarQiitadon (β)
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

Leetcode #147: Insertion Sort List

More than 1 year has passed since last update.
func insertionSortList(_ head: ListNode?) -> ListNode? {
    if head == nil {
        return nil
    let dummyHead = ListNode(0)
    dummyHead.next = head
    var nextNode = head?.next
    head?.next = nil
    while nextNode != nil {
        let tmp = nextNode
        nextNode = nextNode?.next
        var pre = dummyHead
        while pre.next != nil && pre.next!.val < tmp!.val {
            if let node = pre.next {
                pre = node
            } else {
        let node = pre.next
        pre.next = tmp
        pre.next?.next = node

    return dummyHead.next
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away