571
社区成员
发帖
与我相关
我的任务
分享type Node struct {
data interface{}
next *Node
}
type List struct {
length int
head *Node
}
func (list *List) IsEmpty() bool {
if list.length == 0 {
return true
} else {
return false
}
}
func InitList() *List {
node := new(Node)
L := new(List)
L.head = node
return L
}
头插、尾插、指定位置
func (list *List) PushFront(v interface{}) {
node := &Node{data: v}
if list.IsEmpty() {
list.head = node
} else {
node.next = list.head
list.head = node
}
list.length++
}
func (list *List) PushBack(v interface{}) {
node := &Node{data: v}
if list.IsEmpty() {
list.head = node
} else {
cur := list.head
for cur.next != nil {
cur = cur.next
}
cur.next = node
}
list.length++
}
func (list *List) InsertElem(index int, v interface{}) {
if index <= 0 || index > list.length {
fmt.Println("err")
} else {
pre := list.head
node := &Node{data: v}
if index == 1 {
node.next = pre
list.head = node
} else {
for count := 1; count < index-1; count++ {
pre = pre.next
}
node.next = pre.next
pre.next = node
}
list.length--
}
}
元素值、元素下标
func (list *List) DeleteElem(index int) {
if index <= 0 || index > list.length {
fmt.Println("wrong index")
} else {
pre := list.head
if index == 1 {
list.head = pre.next
} else {
pre := list.head
for count := 1; count < index-1; count++ {
pre = pre.next
}
pre.next = pre.next.next
}
list.length--
}
}
func (list *List) Remove(v interface{}) {
pre := list.head
if pre.data == v {
list.head = pre.next
} else {
for pre.next != nil {
if pre.next.data == v {
pre.next = pre.next.next
return
} else {
pre = pre.next
}
}
fmt.Println("fail")
return
}
}
下标得值、值得下标
func (list *List) GetData(index int) int {
if index <= 0 || index > list.length {
return -1
} else {
pre := list.head
for j := 0; j < index-1; j++ {
if pre != nil {
pre = pre.next
}
}
return pre.data.(int)
}
}
func (list *List) GetIdx(v interface{}) int {
cnt := 0
pre := list.head
for pre != nil {
cnt++
if pre.data == v {
return cnt
}
pre = pre.next
}
return -1
}


可以查看测试覆盖多少源码范围