[Go语言]实现链表

链表是一个结点指向下一个结点的存储结构,每一个结点有两个元素,一个是存放数据本身,另一个数据指向下一个结点,由这些结点组成一个链表

思路:

  • 需要先定义一个结点类包含两个元素,一个数据,一个指向下一结点
  • 定义一个链表,包含一个头结点的元素
  • 根据链表中头结点中包含下一个结点循环找到最后的结点,在最后增加新的结点

代码实现

package main

import "fmt"

type Node struct {
    
    
	data int
	next *Node
}

type NodeList struct {
    
    
	headNode *Node
}

func (this *NodeList) add(data int) {
    
    
	node := Node{
    
    data: data, next: nil}
	if this.headNode == nil {
    
    
		this.headNode = &node
	} else {
    
    
		tmp := this.headNode
		for tmp.next != nil {
    
    
			tmp = tmp.next
		}
		tmp.next = &node
	}
}
func (this *NodeList) showall() {
    
    
	if this.headNode == nil {
    
    
		fmt.Println("no data")
	} else {
    
    
		tmp := this.headNode
		for tmp.next != nil {
    
    
			fmt.Println(tmp.data)
			tmp = tmp.next
		}
		fmt.Println(tmp.data)
	}
}
func main() {
    
    
	var nl = new(NodeList)
	nl.add(1)
	nl.add(2)
	nl.add(3)
	nl.add(4)
	nl.showall()
}

猜你喜欢

转载自blog.csdn.net/q291938895/article/details/109061987