R/stack.R
raw| 1 | new_stack <- function() { |
| 2 | |
| 3 | .data <- list() |
| 4 | .index <- 0 |
| 5 | |
| 6 | push <- function(data) { |
| 7 | .index <<- .index + 1 |
| 8 | .data[[.index]] <<- data |
| 9 | } |
| 10 | |
| 11 | pop <- function() { |
| 12 | if (.index == 0) |
| 13 | return(NULL) |
| 14 | |
| 15 | result <- .data[[.index]] |
| 16 | .index <<- .index - 1 |
| 17 | result |
| 18 | } |
| 19 | |
| 20 | peek <- function() { |
| 21 | if (.index == 0) |
| 22 | return(NULL) |
| 23 | .data[[.index]] |
| 24 | } |
| 25 | |
| 26 | list(push = push, pop = pop, peek = peek) |
| 27 | } |
| 28 |