Go语言程序检查栈是否为空


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

算法

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

  • 步骤 2 − 创建一个栈结构,使用一个 item 切片来存储栈元素。

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

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

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

  • 步骤 6 − 它检查 Stack 结构中元素的长度是否等于 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 语言程序,使用迭代和递归方法以及两个示例来检查栈是否为空。在第一个示例中,我们使用了迭代方法,在第二个示例中,我们使用了递归方法。

更新于: 2023年4月3日

194 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.