Go数据结构——链表
package main
import (
"fmt"
)
type list struct {
head *listNode
data int
}
type listNode struct {
next *listNode
data int
}
func newList() *list {
l := list{}
l.head = &listNode{}
return &l
}
func (l *list) append(value int) {
h := l.head
for h.next != nil {
h = h.next
}
h.next = &listNode{data: value}
}
func (l *list) delete(value int) {
for h := l.head; h != nil && h.next != nil; {
if h.next.data == value {
h.next = h.next.next
continue
}
h = h.next
}
}
func (l *list) sort() {
o := l.head.next
l.head.next = nil
for o != nil {
h := l.head
for h.next != nil && h.next.data > o.data {
h = h.next
}
n := o.next
o.next = h.next
h.next = o
o = n
}
}
func (l *list) print() {
fmt.Print("head")
for h := l.head.next; h != nil; h = h.next {
fmt.Print(" -> ", h.data)
}
fmt.Println()
}
func main() {
l := newList()
l.append(1)
l.append(2)
l.append(3)
l.append(4)
l.print()
l.sort()
l.print()
}
![](https://img.haomeiwen.com/i14991910/8e5e517aad856b69.png)
image.png
本文标题:Go数据结构——链表
本文链接:https://www.haomeiwen.com/subject/fffoxhtx.html
网友评论