2021-03-17:手寫代碼:單鏈表插入排序。golang
福大大 答案2021-03-17:ide
從鏈表的第二個節點開始遍歷。當前節點的左邊全部節點必定是有序的。先比較當前節點和左鄰節點,若是左鄰節點小於等於當前節點,直接下個節點;若是左鄰節點大於當前節點,從鏈表的有序部分的第一個節點開始遍歷,找到當前節點小於有序部分的某個節點,而後插入進去。3d
代碼用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} printlnLinkNodeList(head) head = InsertSort(head) printlnLinkNodeList(head) } //Definition for singly-linked list. type ListNode struct { Val int Next *ListNode } //鏈表打印 func printlnLinkNodeList(head *ListNode) { cur := head for cur != nil { fmt.Print(cur.Val, "\t") cur = cur.Next } fmt.Println() } //插入排序 func InsertSort(head *ListNode) *ListNode { if head == nil || head.Next == nil { return head } preAns := &ListNode{Next: head} pre := head cur := head.Next for cur != nil { if pre.Val <= cur.Val { //無論 //下一個循環的準備工做 pre, cur = cur, cur.Next } else { preTemp := preAns temp := preAns.Next for cur.Val >= temp.Val { preTemp, temp = temp, temp.Next } //刪除當前節點 pre.Next = cur.Next //有序節點裏插入當前節點 preTemp.Next, cur.Next = cur, temp //下一個循環的準備工做,pre不變 cur = pre.Next } } return preAns.Next }
執行結果以下:
blog