Stack
Posted: Tue Mar 20, 2007 4:45 pm
This code allows you to create stacks on the fly. The stacks stores longs, which means you can create stacks of pointers to structures if you need to store more complicated things than longs on it.
Overflow and underflow is checked for if the debugger is enabled.
Overflow and underflow is checked for if the debugger is enabled.
Code: Select all
Procedure NewStack(Size.l)
Protected *Long.Long = AllocateMemory((Size+2)*SizeOf(Long))
*Long\l = Size*SizeOf(Long)
ProcedureReturn *Long
EndProcedure
Procedure Push(Stack.l, Value.l)
Protected *Length.Long = Stack+SizeOf(Long)
*Length\l + SizeOf(Long)
CompilerIf #PB_Compiler_Debugger
Protected *Size.Long = Stack
If *Length\l = *Size\l
CallDebugger ; Stack overflow
EndIf
CompilerEndIf
*Length + *Length\l
*Length\l = Value
EndProcedure
Procedure.l Pop(Stack)
Protected *Length.Long = Stack+SizeOf(Long)
Protected *Value.Long
CompilerIf #PB_Compiler_Debugger
If *Length\l < 1
CallDebugger ; Stack underflow
EndIf
CompilerEndIf
*Value = *Length + *Length\l
*Length\l - SizeOf(Long)
ProcedureReturn *Value\l
EndProcedure
Procedure.l Top(Stack)
Protected *Length.Long = Stack+SizeOf(Long)
CompilerIf #PB_Compiler_Debugger
If *Length\l < 1
CallDebugger ; Stack underflow
EndIf
CompilerEndIf
*Length + *Length\l
ProcedureReturn *Length\l
EndProcedure
Procedure DeleteStack(Stack.l)
FreeMemory(Stack)
EndProcedure
Procedure.l IsEmpty(Stack)
Protected *Length.Long = Stack+SizeOf(Long)
If *Length\l
ProcedureReturn 0
EndIf
ProcedureReturn 1
EndProcedure
A = NewStack(160)
Push(A, 5)
Push(A, 10)
Debug IsEmpty(A)
Debug Top(A)
Debug Pop(A)
Debug Pop(A)
Debug IsEmpty(A)