R 是否有一个您不必自己编写代码的堆栈?
从字面上看,我只想从 CS 102 中得到一些东西。
我写了下面的代码,效果很好。但我宁愿有其他更普遍和经过验证的东西。
语言有什么东西吗?还是所有常用算法的一些包,例如队列、树等?
####################################################################################################
# Stack.R - Implments a generalized stack. Uses Reference Classes since we need mutability.
####################################################################################################
Stack <- setRefClass("Stack",
fields = list(
vStack = "vector",
nTop = "numeric"
),
methods = list(
initialize = function() {
nTop <<- 1
},
push = function(nItem) {
vStack <<- c(vStack, nItem)
nTop <<- nTop + 1
vStack[nTop-1]
},
pop = function() {
if (nTop == 1) return(NULL)
nItem <- vStack[nTop-1]
nTop <<- nTop - 1
vStack <<- vStack[1:nTop-1]
nItem
},
top = function() {
vStack[nTop-1]
}
)
)
# StackTest <- function() {
#
# say("Starting...")
# s <- Stack()
# say(s$push(1), " {push}")
# say(s$push("Hello"), " {push}")
# say(s$push(2), " {push}")
# say(s$push("World"), " {push}")
# say(s$push(3), " {push}")
# say(s$top(), " {top}")
# say(s$top(), " {top}")
# say(s$pop(), " {pop}")
# say(s$pop(), " {pop}")
# say(s$pop(), " {pop}")
# say(s$pop(), " {pop}")
# say("Finished.")
#
# }
#
# StackTest()