CO205 Coursework: Abstract Data-Type Graph
AdtStack.PAS
(*
Stack ADT Module
CO205 Coursework: GRAPHS
Eamonn Martin (BSc Computing)
ID: 96D59682
*)
UNIT ADTStack;
INTERFACE
TYPE
sval_t = Integer; (* Stack value type *)
STACKPTR = ^STACK_T; (* Pointer to a stack type *)
STACK_T = Record (* Stack data structure *)
value: sval_t; (* Stack value *)
next: STACKPTR; (* Next stack element *)
End;
(* Set the value of stack to value *)
PROCEDURE SetStackValue (stack: STACKPTR; value: sval_t);
(* Set the next-stack pointer in stack *)
PROCEDURE SetNextStack (stack, next: STACKPTR);
(* Get the value of stack *)
FUNCTION GetStackValue (stack: STACKPTR): sval_t;
(* Return the next-stack pointer in stack *)
FUNCTION GetNextStack (stack: STACKPTR): STACKPTR;
(* Return the number of values in stack *)
FUNCTION StackSize (stack: STACKPTR): Integer;
(* Add value to the top of stack *)
PROCEDURE PushStack (value: sval_t; stack: STACKPTR);
(* Retrieve the value at the top of stack *)
FUNCTION PopStack (stack: STACKPTR): sval_t;
(* Initialize a stack structure *)
PROCEDURE InitStackADT (stack: STACKPTR);
IMPLEMENTATION
(*** Stack ADT Basic Primitives ***)
(* Set the value of stack to value *)
PROCEDURE SetStackValue (stack: STACKPTR; value: sval_t);
BEGIN
stack^.value := value
END;
(* Set the next-stack pointer in stack *)
PROCEDURE SetNextStack (stack, next: STACKPTR);
BEGIN
stack^.next := next
END;
(* Get the value of stack *)
FUNCTION GetStackValue (stack: STACKPTR): sval_t;
BEGIN
GetStackValue := stack^.value
END;
(* Return the next-stack pointer in stack *)
FUNCTION GetNextStack (stack: STACKPTR): STACKPTR;
BEGIN
GetNextStack := stack^.next
END;
(*** Stack ADT Locator ***)
(* Return the number of values in stack *)
FUNCTION StackSize (stack: STACKPTR): Integer;
FUNCTION _StackSize (stack: STACKPTR; n: Integer): Integer;
BEGIN
IF GetNextStack(stack)=Nil THEN _StackSize := n
ELSE _StackSize := _StackSize(GetNextStack(stack), n+1);
END;
BEGIN
StackSize := _StackSize(stack, 0)
END;
(*** Stack ADT Constructor/Destructor ***)
(* Add value to the top of stack *)
PROCEDURE PushStack (value: sval_t; stack: STACKPTR);
VAR
newstack: STACKPTR;
BEGIN
New(newstack); (* Create a new element *)
SetNextStack(newstack, GetNextStack(stack)); (* Point at stack top *)
SetNextStack(stack, newstack); (* Insert at top of list *)
SetStackValue(newstack, value) (* Set element value *)
END;
(* Retrieve the value at the top of stack *)
FUNCTION PopStack (stack: STACKPTR): sval_t;
VAR
oldstack: STACKPTR;
BEGIN
oldstack := GetNextStack(stack); (* Get top element *)
PopStack := GetStackValue(oldstack); (* Get element value *)
SetNextStack(stack, GetNextStack(oldstack)); (* Remove from list *)
Dispose(oldstack); (* Free element *)
END;
(*** Stack ADT Initialization ***)
(* Initialize a stack structure *)
PROCEDURE InitStackADT (stack: STACKPTR);
BEGIN
SetNextStack(stack, Nil);
END;
BEGIN
END.
Go To: CO205 Coursework