2021-03-14:手寫程式碼:單鏈表氣泡排序。
福大大 答案2021-03-14:
遍歷連結串列,算出元素個數,假設為N。需要巢狀迴圈,外迴圈N-1輪,每輪迴圈相鄰交換N-1次。
程式碼用golang編寫,程式碼如下:
package mainimport "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 = BubbleSort(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 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. 排序連結串列](https://leetcode-cn.com/problems/sort-list/)
最新評論