Handwritten code: Insertion sort of singly linked list

Start traversal from the second node of the linked list. All nodes to the left of the current node must be in order. First compare the current node and the left neighbor node. If the left neighbor node is less than or equal to the current node, go directly to the next node; if the left neighbor node is greater than the current node, start traversing from the first node in the ordered part of the linked list, and find that the current node is less than there. A node in the sequence part, and then insert it.

The code is written in golang, the code is as follows:

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
}

The execution results are as follows:
Insert picture description here

 

Guess you like

Origin blog.csdn.net/wangxi06/article/details/114967570