Skip to content

Stack module

Wang Renxin edited this page May 31, 2022 · 14 revisions

MY-BASIC implements two kinds of advanced collections: LIST and DICT. It's also possible to implement another frequently used STACK collection with the prototype-based class in MY-BASIC.

Create a file named stack.bas with following code:

class node
	var dt = nil
	var link = nil
endclass

class stack
	var top = nil

	def empty()
		return top = nil
	enddef

	def push(d)
		n = new(node)
		n.dt = d

		if top = nil then
			top = n
		else
			n.link = top
			top = n
		endif
	enddef

	def pop()
		if top = nil then
			return nil
		endif

		n = top
		top = top.link

		return n.dt
	enddef
endclass

Then use it as follow:

import "stack.bas"

s = new(stack)
s.push(1)
s.push(2)
s.push(3)
while not s.empty()
	print s.pop();
wend

Or another way to do it:

class node
	var dt = nil
	var link = nil
endclass

class stack
	var top = nil
	var count = 0

	def _len()
		return count
	enddef

	def _push(d)
		n = new(node)
		n.dt = d

		if top = nil then
			top = n
		else
			n.link = top
			top = n
		endif

		count = count + 1
	enddef

	def _pop()
		if top = nil then
			return nil
		endif

		n = top
		top = top.link

		count = count - 1

		return n.dt
	enddef
endclass

With the second version, it's possible to apply some built-in functions to these overridden methods as:

import "stack.bas"

s = new(stack)
push(s, 1)
push(s, 2)
push(s, 3)
while len(s) <> 0
	print pop(s);
wend

Read the Using prototype based class page to get information about how to write a class in MY-BASIC.

Clone this wiki locally