用随机数生成结构体链表,然后实现在前面插入,在后面插入,在中间插入,指定节点删除并遍历等。
package main
import (
"fmt"
"math/rand"
)
type Student struct {
Name string
Age int
score float32
next *Student
}
func trans(head *Student) {
p := head
for p != nil {
fmt.Println(*p)
p = p.next
}
}
func listLen(head *Student) int {
var p *Student = head
lenth := 0
for p != nil {
lenth++
p = p.next
}
return lenth
}
func insertHead(p *Student) *Student {
for i := 0; i < 10; i++ {
stu := Student{
Name: fmt.Sprintf("stu%d", i),
Age: rand.Intn(100),
score: rand.Float32() * 100,
}
stu.next = p
p = &stu
}
return p
}
func insertTail(p *Student) *Student {
var head *Student = p
for i := 0; i < 10; i++ {
stu := Student{
Name: fmt.Sprintf("stu%d", i),
Age: rand.Intn(100),
score: rand.Float32() * 100,
}
if head != nil {
p.next = &stu
p = p.next
} else {
head = &stu
p = head
}
}
return head
}
func delNode(head *Student, toDel int) *Student {
var p *Student = head
var pre, tmpNext *Student
lenth := listLen(head)
if toDel > lenth || toDel < 1 {
fmt.Println("No item was deleted.")
return head
} else if toDel == 1 {
head = p.next
} else {
for i := 1; i < toDel; i++ {
pre = p
tmpNext = p.next
p = p.next
}
pre.next = tmpNext.next
}
return head
}
func insertMid(head, toInsItem *Student, toIns int) *Student {
var p *Student = head
var pre *Student
lenth := listLen(head)
if toIns > lenth+1 || toIns < 0 {
fmt.Println("No item was inserted.")
return head
} else {
switch toIns {
case lenth + 1:
for {
if p != nil {
pre = p
p = p.next
} else {
pre.next = toInsItem
break
}
}
case 0, 1:
toInsItem.next = head
head = toInsItem
default:
for i := 1; i < toIns; i++ {
pre = p
p = p.next
}
pre.next = toInsItem
toInsItem.next = p
}
}
return head
}
func main() {
var head1, head2 *Student
fmt.Println("在链表前面插入========")
head1 = insertHead(head1)
trans(head1)
fmt.Println("Current insertHead list1 lenth is: ", listLen(head1))
fmt.Println("在链表后面插入========")
head2 = insertTail(head2)
trans(head2)
fmt.Println("Current insertTail list2 lenth is: ", listLen(head2))
fmt.Println("删除链表list2第3个元素========")
head2 = delNode(head2, 3)
trans(head2)
fmt.Println("After delete, the list2 lenth is: ", listLen(head2))
fmt.Println("删除链表list2第5个元素========")
head2 = delNode(head2, 5)
trans(head2)
fmt.Println("After delete, the list2 lenth is: ", listLen(head2))
var stuadd1 = Student{
Name: "zgx",
Age: 46,
score: 90.3,
}
var stuadd2 = Student{
Name: "hy",
Age: 45,
score: 80.1,
}
var stuadd3 = Student{
Name: "zxy",
Age: 17,
score: 100.0,
}
fmt.Println("在链表list2的第一个位置增加一个元素========")
head2 = insertMid(head2, &stuadd1, 0)
trans(head2)
fmt.Println("After insert, the list2 lenth is: ", listLen(head2))
fmt.Println("在链表list2的第十的位置增加一个元素========")
head2 = insertMid(head2, &stuadd2, 10)
trans(head2)
fmt.Println("After insert, the list2 lenth is: ", listLen(head2))
fmt.Println("在链表list2的第三个位置增加一个元素========")
head2 = insertMid(head2, &stuadd3, 3)
trans(head2)
fmt.Println("After insert, the list2 lenth is: ", listLen(head2))
}