Skip to content

Stack module

Wang Renxin edited this page Jun 14, 2016 · 14 revisions

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

Create a file named stack.bas with following code:

class node
	var data = nil
	var link = nil
endclass

class stack
	var top = nil

	def empty()
		return top = nil
	enddef

	def push(d)
		n = new(node)
		n.data = 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.data
	enddef
endclass

Then write in another file stack_test.bas:

import "stack.bas"

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

Now it's able to reuse the STACK expediently.

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

Clone this wiki locally