Golang 检查栈是否为空

Golang 检查栈是否为空

在本篇Golang文章中,我们将使用迭代和递归方法来检查栈是否为空。栈是一种遵循先进后出(LIFO)原则的线性数据结构。

步骤

  • 第1步 − 首先,我们需要导入fmt和strconv包。

  • 第2步 − 创建一个包含一个项目切片的栈结构,用于存储栈元素。

  • 第3步 − 现在,定义push(),pop()和peek()函数来执行栈的基本操作。

  • 第4步 − push()将项目添加到栈的末尾,而pop()从栈中移除最后一个项目。peek()返回栈的最后一个项目,但不移除它。

  • 第5步 − 现在,创建一个isEmpty()函数,如果栈为空则返回true,否则返回false。

  • 第6步 − 它检查栈结构中的项目长度是否等于0。如果长度为0,则栈为空,函数返回true。否则,如果长度大于0,则栈不为空,函数返回false。

  • 第7步 − 开始main()函数。在main()函数内部,创建一个栈结构并初始化一些项目。

  • 第8步 − 现在,调用isEmpty()函数并将栈作为参数传递给它。

  • 第9步 − 最初,栈为空,所以它返回false。然后,在推入一些项目之后再次调用isEmpty()函数,现在它将返回true。

  • 第10步 − 进一步,在弹出所有项目后,它返回true。

示例1

在这个示例中,我们将定义一个isEmpty()函数,使用迭代方法来检查栈是否为空。

package main

import (
   "fmt"
)

type Stack struct {
   items []int
}

func (s *Stack) push(item int) {
   s.items = append(s.items, item)
}

func (s *Stack) pop() int {
   l := len(s.items) - 1
   item := s.items[l]
   s.items = s.items[:l]
   return item
}

func (s *Stack) peek() int {
   return s.items[len(s.items)-1]
}

func (s *Stack) isEmpty() bool {
   return len(s.items) == 0
}

func main() {
   s := &Stack{}

   fmt.Println("Is the stack empty?", s.isEmpty())

   s.push(4)
   s.push(5)
   s.push(3)

   fmt.Println("Is the stack empty?", s.isEmpty())

   s.pop()
   s.pop()
   s.pop()

   fmt.Println("Is the stack empty?", s.isEmpty())
}

输出

Is the stack empty? true
Is the stack empty? false
Is the stack empty? true

示例2

在此示例中,我们将定义一个isEmpty()函数,用于使用递归方法检查堆栈是否为空。

package main

import "fmt"

type Stack struct {
   items []int
}
func (s *Stack) Push(item int) {
   s.items = append(s.items, item)
}

func (s *Stack) Pop() int {
   if len(s.items) == 0 {
      return -1
   }
   item := s.items[len(s.items)-1]
   s.items = s.items[:len(s.items)-1]
   return item
}

func (s *Stack) isEmpty() bool {
   if len(s.items) == 0 {
      return true
   } else {
      lastItem := s.Pop()
      isEmpty := s.isEmpty()
      s.Push(lastItem)
      return isEmpty
   }
}

func main() {
   s := Stack{}
   s.Pop()
   s.Pop()
   s.Pop()

   fmt.Println("Is the stack empty?", s.isEmpty())
}

输出

Is the stack empty? true

结论

我们成功编译和执行了一个go语言程序,使用迭代和递归方法来检查堆栈是否为空,并提供了两个示例。在第一个示例中,我们使用了迭代方法,在第二个示例中,我们使用了递归方法。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程