Taking out second element from Stack
I am learning Scala. Ho开发者_JS百科wever, on the exercise, I have some problem with Stack. How can I remove the second element from stack. I have to remove second element and put back the top element.
Thanks your advance
i dont know scala but normally you would do
variable = pop()
pop()
push(variable)
save the first element, pop the second one to nirvana and then push the first element on top again
I know nothing about Scala, but a stack is a stack.
Call pop
on the stack and assign the returned value to a temporary variable, then pop again and push back the element you assigned with the first call tot pop
.
Pseudo code:
tempVar = stack.pop();
stack.pop();
stack.push(tempVar);
Not much difference between a Stack and a List, and the Scala API documentation says this as well.
If using a List, a different approach to this is:
val result: (Option[T], List[T]) = myList match {
case first :: x :: rest => (Some(x), first :: rest)
case list => (None, list)
}
The explicit type on the result is for clarity. The advantage to this is you wont throw an exception if there is no second item, and it is a decent example of how to use pattern matching.
精彩评论