怎么用go实现一个栈

题目来源

答案1:

  1. //一个队列
  2. type MyStack struct {
  3. queue []int
  4. }
  5. func Constructor() MyStack {
  6. return MyStack{
  7. queue: make([]int, 0),
  8. }
  9. }
  10. func (this *MyStack) Push(x int) {
  11. this.queue = append(this.queue, x)
  12. }
  13. func (this *MyStack) Pop() int {//出队操作
  14. n := len(this.queue)-1
  15. for n!=0{ ////除了最后一个,其余的都重新添加到队列里
  16. val := this.queue[0]
  17. this.queue = this.queue[1:]
  18. this.queue = append(this.queue, val)
  19. n--
  20. }//新入队元素x到了最前面,出队时直接出-》后入先出
  21. val := this.queue[0]
  22. this.queue = this.queue[1:]
  23. return val
  24. }
  25. func (this *MyStack) Top() int {
  26. val := this.Pop()
  27. this.queue = append(this.queue, val)
  28. return val
  29. }
  30. func (this *MyStack) Empty() bool {
  31. if len(this.queue)==0{
  32. return true
  33. }
  34. return false
  35. }