GO语言使用数组实现栈和队列

313 阅读1分钟

实现栈和队列可以使用链表,也可以使用数组
使用数组的优点缺点

  • 使用数组的优点:可以访问其中随机的一个元素,并且更改
  • 使用数组的缺点:输入在数组中插入一个元素,会移动该索引之后的所有元素
  • 使用链表的优点:可以在不改变元素相对位置的情况下,删除其中的某一个元素,或插入元素,只改变前后的地址即可
  • 使用链表的缺点:不可以访问链表中随机的一个数值,需要遍历链表。
    关于链表实现栈和队列,之前的博客已经介绍过,这次介绍使用数组实现栈和队列
const N int = 1e6

type Student struct { //设置结构体
	base  *int   //基指针
	idnum [N]int //数组
	top   *int   //头指针
}

func push(head *Student, dis []int) (bool, *Student) {
	count := *head.top        //将头指针
	for _, num := range dis { //遍历需要插入的数组
		head.idnum[*head.top] = num //将遍历的元素放入数组中
		count++                     //进行插入数组位置索引的增加
		head.top = &count
	}
	return true, head
}
func pop(head *Student) (bool, int) { //栈,尾部弹出元素
	if *head.top == 0 { //如果头部指针为0,则数组为空,返回false , 0
		return false, 0
	}
	*head.top--                        //将指针指向的索引-1
	return true, head.idnum[*head.top] //返回true和数组最后的元素
}
func hpop(head *Student) (bool, int) { //队列,头部弹出元素
	if *head.top == 0 { //判断数组是否为空,如果为空则返回false , 0
		return false, 0
	}
	temp := head.idnum[*head.base] //将要返回的数组首元素赋值给临时变量
	*head.base++                   //将头指针+1
	return true, temp              //返回true , temp
}