2021-03-14:手寫代碼:單鏈表冒泡排序。golang
福大大 答案2021-03-14:ide
遍歷鏈表,算出元素個數,假設爲N。須要嵌套循環,外循環N-1輪,每輪循環相鄰交換N-1次。指針
代碼用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 = 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 }
執行結果以下:
blog