Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- type
- List{.unchecked.}[T] = array[0..0, T]
- Stack[T] = object
- size: Natural
- head: int
- data: ptr List[T]
- proc new_stack[T](size: Natural = 2): Stack[T] =
- var data = cast[ptr List[T]](alloc(size * sizeof(T)))
- return Stack[T](size: size, head: -1, data: data)
- proc destroy_stack(stack: Stack) =
- if stack.data != nil:
- dealloc stack.data
- echo "destroy stack."
- proc `[]`[T](stack: Stack[T], i: Natural): T =
- if i >= stack.size:
- raise newException(IndexError, "request for index out of bounds.")
- return stack.data[][int(i)]
- proc `[]=`[T](stack: Stack[T], i: Natural, item: T) =
- if i >= stack.size:
- raise newException(IndexError, "request to set out of bounds index.")
- stack.data[][int(i)] = item
- proc peek[T](stack: Stack[T]): T =
- if stack.head < 0:
- raise newException(IndexError, "inspect on empty stack.")
- result = stack.data[stack.head]
- proc push[T](stack: Stack[T], item: T) =
- if stack.head == stack.size - 1:
- var data_expanded = cast[ptr List[T]](alloc(stack.size * 2 * sizeof(T)))
- copyMem(data_expanded, stack.data, stack.size)
- dealloc(stack.data)
- stack.data = data_expanded
- echo("expand stack.")
- stack.head += 1
- stack[stack.head] = item
- block:
- var stack = new_stack[int]()
- echo(stack.size)
- for i in 0..<stack.size:
- echo(stack[i])
- stack.push(i + 2)
- for i in 0..<stack.size:
- echo(stack.peek())
- destroy_stack(stack)
Add Comment
Please, Sign In to add comment