简体   繁体   English

如何将Scala列表用作堆栈?

[英]How can I use a Scala List as a Stack?

I am trying to solve a hw problem in Scala. 我正在尝试解决Scala中的硬件问题。 A traditional solution require a stack but stacks have not been introduced in the class so far. 传统的解决方案需要堆栈,但是到目前为止,该类还没有引入堆栈。 Only lists have been introduced. 仅介绍了列表。 My question is how can treat a list as a stack? 我的问题是如何将列表视为堆栈? In other words, how can I mimic pushing and popping elements on a list? 换句话说,如何模仿列表中的元素推入和弹出?

I hope this will show the idea: 我希望这能显示出这个主意:

scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)

scala> val pushed0 = 0::x
push3: List[Int] = List(0, 1, 2, 3)

scala> val pop0 = pushed0.head
pop3: Int = 0
// it is actually more peek than fair pop 

scala> val stackAfterPop = pushed0.tail
stackAfterPop: List[Int] = List(1, 2, 3)

It will actually have much better syntax when you'll be acquainted with pattern matching (next week I guess): 当您熟悉模式匹配时,它实际上将具有更好的语法(我猜是下周):

scala> val popped::stack = pushed0
popped: Int = 0
stack: List[Int] = List(1, 2, 3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM