单链表(Single Linked List)是链表数据结构的一种实现方式,它包含一系列节点(Node),每个节点都包含一个数据域和一个指向下一个节点的指针。与数组相比,链表的一个主要优点是它们可以动态地进行扩展和收缩,因为它们的元素在内存中不是连续存储的。
通过定义结构体实现单链表的操作,no为链表中节点的id,name为节点id对应的内容,next为下一个节点的信息 - type HeroNode struct {
- no int
- name string
- next *HeroNode
- }
复制代码InputNode方法,为链表添加节点。通过定义辅助节点,找到链表的最后一个节点,并将要添加的节点添加到找到的节点的下一个节点。 - func InputNode(head *HeroNode, hero *HeroNode) {
- text := head
- for {
- if text.next == nil {
- break
- }
- text = text.next
- }
- text.next = hero
- }
复制代码InputNode2方法,为链表顺序添加节点。首先还是定义一个辅助节点,这次还另外定义一个flag为了判断要插入的节点是否已经存在。通过辅助节点进行判断插入的节点的id,并进行插入对应位置。这里要注意的是需要先将要插入的节点的下一个节点改为辅助节点的下一个节点,然后再将辅助节点的下一个节点换为要插入的节点。一旦先将text.next=hero,原本text后面的节点将会失去前置节点,那么hero节点将添加失败 - func InputNode2(head *HeroNode, hero *HeroNode) {
- text := head
- flag := true
- //让插入的节点的no,和text的下一个节点的no进行比较
- for {
- if text.next == nil {
- break
- } else if text.next.no > hero.no {
- //说明hero应该插入到text后面
- break
- } else if text.next.no == hero.no {
- flag = false
- break
- }
- text = text.next
- }
- if !flag {
- fmt.Println("已经存在", hero.no)
- return
- } else {
- hero.next = text.next
- text.next = hero
- }
- }
复制代码DelectNode方法,删除链表中的节点。通过定义辅助节点和flag进行对要删除节点的查询,查询后 将text的下一个节点指向text下一个节点的下一个节点即可完成节点的删除。 - func DelectNode(hero *HeroNode, id int) {
- text := hero
- flag := false
- for {
- if text.next == nil {
- break
- } else if text.next.no == id {
- //说明找到了
- flag = true
- break
- }
- text = text.next
- }
- if flag {
- text.next = text.next.next
- } else {
- fmt.Println("删除id不存在", id)
- }
- }
复制代码ShowNode方法,实现显示链表中的节点。先判断链表是否为空链表然后进行链表的打印输出,直到链表为空。 - func ShowNode(head *HeroNode) {
- // 创建一个辅助节点
- text := head
- // 判断是否为空链表
- if text.next == nil {
- fmt.Println("空链表")
- return
- }
- for {
- fmt.Printf("[%d ,%s ]==>", text.next.no, text.next.name)
- text = text.next
- if text.next == nil {
- break
- }
- }
- }
复制代码主函数。定义了一个根节点head,定义了5个要添加的节点,并将他们按照顺序添加,之后打印显示出整个链表,然后删除掉节点id为"1"的数据,并再次打印显示链表。 - func main() {
- // 创建根节点
- head := &HeroNode{}
- hero1 := &HeroNode{
- no: 1,
- name: "张明",
- }
- hero2 := &HeroNode{
- no: 2,
- name: "李华",
- }
- hero3 := &HeroNode{
- no: 3,
- name: "王五",
- }
- hero4 := &HeroNode{
- no: 4,
- name: "张三",
- }
- hero5 := &HeroNode{
- no: 5,
- name: "花花",
- }
- InputNode2(head, hero1)
- InputNode2(head, hero2)
- InputNode2(head, hero3)
- InputNode2(head, hero4)
- InputNode2(head, hero5)
- ShowNode(head)
- fmt.Println()
- DelectNode(head, 1)
- ShowNode(head)
- }
复制代码整体代码的实现
以上就是Golang使用切片实现单链表的示例代码的详细内容,更多关于Golang切片单链表的资料请关注晓枫资讯其它相关文章!
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |