2021-03-15:手寫代碼:單鏈表選擇排序。

2021-03-15:手寫代碼:單鏈表選擇排序。golang

福大大 答案2021-03-15:ide

遍歷鏈表,找出最小元素,鏈表裏刪除最小元素,最小元素放在須要返回的鏈表裏。指針

代碼用golang編寫,代碼以下:code

package main

import "fmt"

func main() {
    //head := &ListNode{Val: 4}
    //head.Next = &ListNode{Val: 2}
    //head.Next.Next = &ListNode{Val: 1}
    //head.Next.Next.Next = &ListNode{Val: 3}

    head := &ListNode{Val: -1}
    head.Next = &ListNode{Val: 5}
    head.Next.Next = &ListNode{Val: 3}
    head.Next.Next.Next = &ListNode{Val: 4}
    head.Next.Next.Next.Next = &ListNode{Val: 0}

    cur := head
    for cur != nil {
        fmt.Print(cur.Val, "\t")
        cur = cur.Next
    }
    fmt.Println()

    head = SelectSort(head)

    cur = head
    for cur != nil {
        fmt.Print(cur.Val, "\t")
        cur = cur.Next
    }
    fmt.Println()
}

//Definition for singly-linked list.
type ListNode struct {
    Val  int
    Next *ListNode
}

//選擇排序
func SelectSort(head *ListNode) *ListNode {
    if head == nil || head.Next == nil {
        return head
    }

    //有換頭的可能,因此新增一個虛擬頭節點
    preAns := &ListNode{}
    preAnsEnd := preAns
    preHead := &ListNode{Next: head}

    //選擇
    var pre, cur, preSel, sel *ListNode
    for preHead.Next != nil {
        pre, cur = preHead, preHead.Next

        //默認選中第1個節點
        preSel, sel = pre, cur

        //選最小的,從第2個節點開始
        pre, cur = cur, cur.Next
        for cur != nil {
            if cur.Val < sel.Val {
                preSel, sel = pre, cur
            }
            pre, cur = cur, cur.Next
        }

        //選中的節點放在答案裏
        preAnsEnd.Next = sel

        //原鏈表刪除選中的節點
        preSel.Next = sel.Next

        //尾指針指向Next
        preAnsEnd = preAnsEnd.Next
    }

    //虛擬頭節點的Next指針就是須要返回的節點
    return preAns.Next
}

執行結果以下:
圖片blog


力扣148. 排序鏈表
評論排序

相關文章
相關標籤/搜索