• 2021-03-14:手写代码:单链表冒泡排序。


    2021-03-14:手写代码:单链表冒泡排序。

    福大大 答案2021-03-14:

    遍历链表,算出元素个数,假设为N。需要嵌套循环,外循环N-1轮,每轮循环相邻交换N-1次。

    代码用golang编写,代码如下:

    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, "	")
            cur = cur.Next
        }
        fmt.Println()
    
        head = BubbleSort(head)
    
        cur = head
        for cur != nil {
            fmt.Print(cur.Val, "	")
            cur = cur.Next
        }
        fmt.Println()
    }
    
    //Definition for singly-linked list.
    type ListNode struct {
        Val  int
        Next *ListNode
    }
    
    //冒泡排序
    func BubbleSort(head *ListNode) *ListNode {
        if head == nil || head.Next == nil {
            return head
        }
    
        //链表节点的个数
        count := 0
    
        //对链表节点计数
        temp := head.Next
        for temp != nil {
            count++
            temp = temp.Next
        }
    
        //有换头的可能,所以新增一个虚拟头节点
        preHead := &ListNode{Next: head}
    
        //冒泡
        var pre, cur *ListNode
        for i := 0; i < count; i++ {
            pre = preHead
            cur = preHead.Next
            for j := 0; j < count-i; j++ {
                if cur.Val > cur.Next.Val {
                    //相邻交换
                    pre.Next, cur.Next, cur.Next.Next, cur = cur.Next, cur.Next.Next, cur, cur.Next
                }
                pre = pre.Next
                cur = cur.Next
            }
        }
    
        //虚拟头节点的Next指针就是需要返回的节点
        return preHead.Next
    }
    

    执行结果如下:
    图片


    力扣148. 排序链表
    评论

  • 相关阅读:
    webrtc 手机端视频旋转
    gstreamer 命令行一些demo
    git一些命令记录
    libnice的问题记录
    webrtc ice 协商一些记录
    linux 挂在windows目录
    leetcode Permutation Sequence
    gstreamer 接收rtsp存储为h264
    uva 10285
    AndroidStudio VS Eclipse快捷键
  • 原文地址:https://www.cnblogs.com/waitmoon/p/14534667.html
Copyright © 2020-2023  润新知