Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

5
Task/Stack/00-META.yaml Normal file
View file

@ -0,0 +1,5 @@
---
category:
- Encyclopedia
from: http://rosettacode.org/wiki/Stack
note: Data Structures

40
Task/Stack/00-TASK.txt Normal file
View file

@ -0,0 +1,40 @@
{{data structure}}[[Category:Classic CS problems and programs]]
A '''stack''' is a container of elements with &nbsp; <big><u>l</u>ast <u>i</u>n, <u>f</u>irst <u>o</u>ut</big> &nbsp; access policy. &nbsp; Sometimes it also called '''LIFO'''.
The stack is accessed through its '''top'''.
The basic stack operations are:
* &nbsp; ''push'' &nbsp; stores a new element onto the stack top;
* &nbsp; ''pop'' &nbsp; returns the last pushed stack element, while removing it from the stack;
* &nbsp; ''empty'' &nbsp; tests if the stack contains no elements.
<br>
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
* &nbsp; ''top'' &nbsp; (sometimes called ''peek'' to keep with the ''p'' theme) returns the topmost element without modifying the stack.
<br>
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way ('''LIFO''') of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See [[wp:Stack_automaton|stack machine]].
Many algorithms in pattern matching, compiler construction (e.g. [[wp:Recursive_descent|recursive descent parsers]]), and machine learning (e.g. based on [[wp:Tree_traversal|tree traversal]]) have a natural representation in terms of stacks.
;Task:
Create a stack supporting the basic operations: push, pop, empty.
{{Template:See also lists}}
<br><br>

7
Task/Stack/11l/stack.11l Normal file
View file

@ -0,0 +1,7 @@
[Int] stack
L(i) 1..10
stack.append(i)
L 10
print(stack.pop())

View file

@ -0,0 +1 @@
PHA

View file

@ -0,0 +1 @@
PLA

View file

@ -0,0 +1,3 @@
TSX
CPX $FF
BEQ stackEmpty

View file

@ -0,0 +1,2 @@
TSX
LDA $0101,x

View file

@ -0,0 +1,2 @@
LEA userStack,A0 ;initialize the user stack, points to a memory address in user RAM. Only do this once!
MOVEM.L D0-D3,-(A0) ;moves the full 32 bits of registers D0,D1,D2,D3 into the address pointed by A0, with pre-decrement

View file

@ -0,0 +1 @@
MOVEM.L (A0)+,D0-D3 ;returns the four longs stored in the stack back to where they came from.

View file

@ -0,0 +1,2 @@
CMPA.L #userStack,A0
BEQ StackIsEmpty

View file

@ -0,0 +1 @@
LEA (4,SP),SP ;does the same thing to the stack as popping 4 bytes, except those bytes are not retrieved.

View file

@ -0,0 +1,2 @@
MOVE.W (SP),D0 ;load the top two bytes of the stack into D0
MOVE.W (A0),D0 ;load the top two bytes of A0 into D0

View file

@ -0,0 +1,2 @@
push ax ;push ax onto the stack
pop ax ; pop the top two bytes of the stack into ax

View file

@ -0,0 +1,3 @@
;get the top item of the stack
pop ax
push ax

205
Task/Stack/ABAP/stack.abap Normal file
View file

@ -0,0 +1,205 @@
report z_stack.
interface stack.
methods:
push
importing
new_element type any
returning
value(new_stack) type ref to stack,
pop
exporting
top_element type any
returning
value(new_stack) type ref to stack,
empty
returning
value(is_empty) type abap_bool,
peek
exporting
top_element type any,
get_size
returning
value(size) type int4,
stringify
returning
value(stringified_stack) type string.
endinterface.
class character_stack definition.
public section.
interfaces:
stack.
methods:
constructor
importing
characters type string optional.
private section.
data:
characters type string.
endclass.
class character_stack implementation.
method stack~push.
characters = |{ new_element }{ characters }|.
new_stack = me.
endmethod.
method stack~pop.
if not me->stack~empty( ).
top_element = me->characters(1).
me->characters = me->characters+1.
endif.
new_stack = me.
endmethod.
method stack~empty.
is_empty = xsdbool( strlen( me->characters ) eq 0 ).
endmethod.
method stack~peek.
check not me->stack~empty( ).
top_element = me->characters(1).
endmethod.
method stack~get_size.
size = strlen( me->characters ).
endmethod.
method stack~stringify.
stringified_stack = cond string(
when me->stack~empty( )
then `empty`
else me->characters ).
endmethod.
method constructor.
check characters is not initial.
me->characters = characters.
endmethod.
endclass.
class integer_stack definition.
public section.
interfaces:
stack.
methods:
constructor
importing
integers type int4_table optional.
private section.
data:
integers type int4_table.
endclass.
class integer_stack implementation.
method stack~push.
append new_element to me->integers.
new_stack = me.
endmethod.
method stack~pop.
if not me->stack~empty( ).
top_element = me->integers[ me->stack~get_size( ) ].
delete me->integers index me->stack~get_size( ).
endif.
new_stack = me.
endmethod.
method stack~empty.
is_empty = xsdbool( lines( me->integers ) eq 0 ).
endmethod.
method stack~peek.
check not me->stack~empty( ).
top_element = me->integers[ lines( me->integers ) ].
endmethod.
method stack~get_size.
size = lines( me->integers ).
endmethod.
method stack~stringify.
stringified_stack = cond string(
when me->stack~empty( )
then `empty`
else reduce string(
init stack = ``
for integer in me->integers
next stack = |{ integer }{ stack }| ) ).
endmethod.
method constructor.
check integers is not initial.
me->integers = integers.
endmethod.
endclass.
start-of-selection.
data:
stack1 type ref to stack,
stack2 type ref to stack,
stack3 type ref to stack,
top_character type char1,
top_integer type int4.
stack1 = new character_stack( ).
stack2 = new integer_stack( ).
stack3 = new integer_stack( ).
write: |Stack1 = { stack1->stringify( ) }|, /.
stack1->push( 'a' )->push( 'b' )->push( 'c' )->push( 'd' ).
write: |push a, push b, push c, push d -> Stack1 = { stack1->stringify( ) }|, /.
stack1->pop( )->pop( importing top_element = top_character ).
write: |pop, pop and return element -> { top_character }, Stack1 = { stack1->stringify( ) }|, /, /.
write: |Stack2 = { stack2->stringify( ) }|, /.
stack2->push( 1 )->push( 2 )->push( 3 )->push( 4 ).
write: |push 1, push 2, push 3, push 4 -> Stack2 = { stack2->stringify( ) }|, /.
stack2->pop( )->pop( importing top_element = top_integer ).
write: |pop, pop and return element -> { top_integer }, Stack2 = { stack2->stringify( ) }|, /, /.
write: |Stack3 = { stack3->stringify( ) }|, /.
stack3->pop( ).
write: |pop -> Stack3 = { stack3->stringify( ) }|, /, /.

View file

@ -0,0 +1,15 @@
# -*- coding: utf-8 -*- #
CO REQUIRES:
MODE OBJVALUE = ~ # Mode/type of actual obj to be stacked #
END CO
MODE OBJNEXTLINK = STRUCT(
REF OBJNEXTLINK next,
OBJVALUE value # ... etc. required #
);
PROC obj nextlink new = REF OBJNEXTLINK:
HEAP OBJNEXTLINK;
PROC obj nextlink free = (REF OBJNEXTLINK free)VOID:
next OF free := obj stack empty # give the garbage collector a BIG hint #

View file

@ -0,0 +1,57 @@
# -*- coding: utf-8 -*- #
CO REQUIRES:
MODE OBJNEXTLINK = STRUCT(
REF OBJNEXTLINK next,
OBJVALUE value
);
PROC obj nextlink new = REF OBJNEXTLINK: ~,
PROC obj nextlink free = (REF OBJNEXTLINK free)VOID: ~
END CO
# actually a pointer to the last LINK, there ITEMs are ADDED, pushed & popped #
MODE OBJSTACK = REF OBJNEXTLINK;
OBJSTACK obj stack empty = NIL;
BOOL obj stack par = FALSE; # make code thread safe #
SEMA obj stack sema = LEVEL ABS obj stack par;
# Warning: 1 SEMA for all stacks of type obj, i.e. not 1 SEMA per stack #
PROC obj stack init = (REF OBJSTACK self)REF OBJSTACK:
self := obj stack empty;
# see if the program/coder wants the OBJ problem mended... #
PROC (REF OBJSTACK #self#)BOOL obj stack index error mended
:= (REF OBJSTACK self)BOOL: (abend("obj stack index error"); stop);
PROC on obj stack index error = (REF OBJSTACK self, PROC(REF OBJSTACK #self#)BOOL mended)VOID:
obj stack index error mended := mended;
PROC obj stack push = (REF OBJSTACK self, OBJVALUE obj)REF OBJSTACK:(
IF obj stack par THEN DOWN obj stack sema FI;
self := obj nextlink new := (self, obj);
IF obj stack par THEN UP obj stack sema FI;
self
);
# aliases: define a useful put (+=:) operator... #
OP +=: = (OBJVALUE obj, REF OBJSTACK self)REF OBJSTACK: obj stack push(self, obj);
PROC obj stack pop = (REF OBJSTACK self)OBJVALUE: (
# DOWN obj stack sema; #
IF self IS obj stack empty THEN
IF NOT obj stack index error mended(self) THEN abend("obj stack index error") FI FI;
OBJNEXTLINK old head := self;
OBJSTACK new head := next OF self;
OBJVALUE out := value OF old head;
obj nextlink free(old head); # freeing nextlink, NOT queue! #
self := new head;
#;UP obj stack sema; #
out
);
PROC obj stack is empty = (REF OBJSTACK self)BOOL:
self IS obj stack empty;
SKIP

View file

@ -0,0 +1,15 @@
# -*- coding: utf-8 -*- #
MODE DIETITEM = STRUCT(
STRING food, annual quantity, units, REAL cost
);
# Stigler's 1939 Diet ... #
FORMAT diet item fmt = $g": "g" "g" = $"zd.dd$;
[]DIETITEM stigler diet = (
("Cabbage", "111","lb.", 4.11),
("Dried Navy Beans", "285","lb.", 16.80),
("Evaporated Milk", "57","cans", 3.84),
("Spinach", "23","lb.", 1.85),
("Wheat Flour", "370","lb.", 13.33),
("Total Annual Cost", "","", 39.93)
)

View file

@ -0,0 +1,20 @@
#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
MODE OBJVALUE = DIETITEM;
PR read "prelude/next_link.a68" PR;
PR read "prelude/stack_base.a68" PR;
PR read "test/data_stigler_diet.a68" PR;
OBJSTACK example stack; obj stack init(example stack);
FOR i TO UPB stigler diet DO
# obj stack push(example stack, stigler diet[i]) #
stigler diet[i] +=: example stack
OD;
printf($"Items popped in reverse:"l$);
WHILE NOT obj stack is empty(example stack) DO
# OR example stack ISNT obj stack empty #
printf((diet item fmt, obj stack pop(example stack), $l$))
OD

View file

@ -0,0 +1,45 @@
MODE DIETITEM = STRUCT (
STRING food, annual quantity, units, REAL cost
);
MODE OBJVALUE = DIETITEM;
# PUSH element to stack #
OP +:= = (REF FLEX[]OBJVALUE stack, OBJVALUE item) VOID:
BEGIN
FLEX[UPB stack + 1]OBJVALUE newstack;
newstack[2:UPB newstack] := stack;
newstack[1] := item;
stack := newstack
END;
OP POP = (REF FLEX[]OBJVALUE stack) OBJVALUE:
IF UPB stack > 0 THEN
OBJVALUE result = stack[1];
stack := stack[2:UPB stack];
result
ELSE
# raise index error; # SKIP
FI;
# Stigler's 1939 Diet ... #
FORMAT diet item fmt = $g": "g" "g" = $"zd.dd$;
[]DIETITEM stigler diet = (
("Cabbage", "111","lb.", 4.11),
("Dried Navy Beans", "285","lb.", 16.80),
("Evaporated Milk", "57","cans", 3.84),
("Spinach", "23","lb.", 1.85),
("Wheat Flour", "370","lb.", 13.33),
("Total Annual Cost", "","", 39.93)
);
FLEX[0]DIETITEM example stack;
FOR i TO UPB stigler diet DO
example stack +:= stigler diet[i]
OD;
printf($"Items popped in reverse:"l$);
WHILE UPB example stack > 0 DO
printf((diet item fmt, POP example stack, $l$))
OD

View file

@ -0,0 +1,48 @@
begin
% define a Stack type that will hold StringStackElements %
% and the StringStackElement type %
% we would need separate types for other element types %
record StringStack ( reference(StringStackElement) top );
record StringStackElement ( string(8) element
; reference(StringStackElement) next
);
% adds e to the end of the StringStack s %
procedure pushString ( reference(StringStack) value s
; string(8) value e
) ;
top(s) := StringStackElement( e, top(s) );
% removes and returns the top element from the StringStack s %
% asserts the Stack is not empty, which will stop the %
% program if it is %
string(8) procedure popString ( reference(StringStack) value s ) ;
begin
string(8) v;
assert( not isEmptyStringStack( s ) );
v := element(top(s));
top(s):= next(top(s));
v
end popStringStack ;
% returns the top element of the StringStack s %
% asserts the Stack is not empty, which will stop the %
% program if it is %
string(8) procedure peekStringStack ( reference(StringStack) value s ) ;
begin
assert( not isEmptyStringStack( s ) );
element(top(s))
end popStringStack ;
% returns true if the StringStack s is empty, false otherwise %
logical procedure isEmptyStringStack ( reference(StringStack) value s ) ; top(s) = null;
begin % test the StringStack operations %
reference(StringStack) s;
s := StringStack( null );
pushString( s, "up" );
pushString( s, "down" );
pushString( s, "strange" );
pushString( s, "charm" );
while not isEmptyStringStack( s ) do write( popString( s )
, if isEmptyStringStack( s ) then "(empty)"
else peekStringStack( s )
)
end
end.

View file

@ -0,0 +1,3 @@
STMFD sp!,{r0-r12,lr} ;push r0 thru r12 and the link register
LDMFD sp!,{r0-r12,pc} ;pop r0 thru r12, and the value that was in the link register is put into the program counter.
;This acts as a pop and return command all-in-one. (Most programs use bx lr to return.)

View file

@ -0,0 +1 @@
LDR r0,[sp] ;load the top of the stack into r0

View file

@ -0,0 +1,9 @@
;this example uses VASM syntax which considers a "word" to be 16-bit regardless of the architecture
InitStackPointer: .long 0x3FFFFFFF ;other assemblers would call this a "word"
MOV R1,#InitStackPointer
LDR SP,[R1] ;set up the stack pointer
LDR R2,[R1] ;also load it into R2
;There's no point in checking since we haven't pushed/popped anything but just for demonstration purposes we'll check now
CMP SP,R2
BEQ StackIsEmpty

190
Task/Stack/ATS/stack.ats Normal file
View file

@ -0,0 +1,190 @@
(* Stacks implemented as linked lists. *)
(* A nonlinear stack type of size n, which is good for when you are
using a garbage collector or can let the memory leak. *)
typedef stack_t (t : t@ype+, n : int) = list (t, n)
typedef stack_t (t : t@ype+) = [n : int] stack_t (t, n)
(* A linear stack type of size n, which requires (and will enforce)
explicit freeing. (Note that a "peek" function for a linear stack
is a complicated topic. But the task avoids this issue.) *)
viewtypedef stack_vt (vt : vt@ype+, n : int) = list_vt (vt, n)
viewtypedef stack_vt (vt : vt@ype+) = [n : int] stack_vt (vt, n)
(* Proof that a given nonlinear stack does not have a nonnegative
size. *)
prfn
lemma_stack_t_param {n : int} {t : t@ype}
(stack : stack_t (t, n)) :<prf>
[0 <= n] void =
lemma_list_param stack
(* Proof that a given linear stack does not have a nonnegative
size. *)
prfn
lemma_stack_vt_param {n : int} {vt : vt@ype}
(stack : !stack_vt (vt, n)) :<prf>
[0 <= n] void =
lemma_list_vt_param stack
(* Create an empty nonlinear stack. *)
fn {}
stack_t_nil {t : t@ype} () :<> stack_t (t, 0) =
list_nil ()
(* Create an empty linear stack. *)
fn {}
stack_vt_nil {vt : vt@ype} () :<> stack_vt (vt, 0) =
list_vt_nil ()
(* Is a nonlinear stack empty? *)
fn {}
stack_t_is_empty {n : int} {t : t@ype}
(stack : stack_t (t, n)) :<>
[empty : bool | empty == (n == 0)]
bool empty =
case+ stack of
| list_nil _ => true
| list_cons _ => false
(* Is a linear stack empty? *)
fn {}
stack_vt_is_empty {n : int} {vt : vt@ype}
(* ! = pass by value; stack is preserved. *)
(stack : !stack_vt (vt, n)) :<>
[empty : bool | empty == (n == 0)]
bool empty =
case+ stack of
| list_vt_nil _ => true
| list_vt_cons _ => false
(* Push to a nonlinear stack that is stored in a variable. *)
fn {t : t@ype}
stack_t_push {n : int}
(stack : &stack_t (t, n) >> stack_t (t, m),
x : t) :<!wrt>
(* It is proved that the stack is raised one higher. *)
#[m : int | 1 <= m; m == n + 1]
void =
let
prval _ = lemma_stack_t_param stack
prval _ = prop_verify {0 <= n} ()
in
stack := list_cons (x, stack)
end
(* Push to a linear stack that is stored in a variable. Beware: if x
is linear, it is consumed. *)
fn {vt : vt@ype}
stack_vt_push {n : int}
(stack : &stack_vt (vt, n) >> stack_vt (vt, m),
x : vt) :<!wrt>
(* It is proved that the stack is raised one higher. *)
#[m : int | 1 <= m; m == n + 1]
void =
let
prval _ = lemma_stack_vt_param stack
prval _ = prop_verify {0 <= n} ()
in
stack := list_vt_cons (x, stack)
end
(* Pop from a nonlinear stack that is stored in a variable. It is
impossible (unless you cheat the typechecker) to pop from an empty
stack. *)
fn {t : t@ype}
stack_t_pop {n : int | 1 <= n}
(stack : &stack_t (t, n) >> stack_t (t, m)) :<!wrt>
(* It is proved that the stack is lowered by one. *)
#[m : int | m == n - 1]
t =
case+ stack of
| list_cons (x, tail) =>
begin
stack := tail;
x
end
(* Pop from a linear stack that is stored in a variable. It is
impossible (unless you cheat the typechecker) to pop from an empty
stack. *)
fn {vt : vt@ype}
stack_vt_pop {n : int | 1 <= n}
(stack : &stack_vt (vt, n) >> stack_vt (vt, m)) :<!wrt>
(* It is proved that the stack is lowered by one. *)
#[m : int | m == n - 1]
vt =
case+ stack of
| ~ list_vt_cons (x, tail) => (* ~ = the top node is consumed. *)
begin
stack := tail;
x
end
(* A linear stack has to be consumed. *)
extern fun {vt : vt@ype}
stack_vt_free$element_free (x : vt) :<> void
fn {vt : vt@ype}
stack_vt_free {n : int}
(stack : stack_vt (vt, n)) :<> void =
let
fun
loop {m : int | 0 <= m}
.<m>. (* <-- proof of loop termination *)
(stk : stack_vt (vt, m)) :<> void =
case+ stk of
| ~ list_vt_nil () => begin end
| ~ list_vt_cons (x, tail) =>
begin
stack_vt_free$element_free x;
loop tail
end
prval _ = lemma_stack_vt_param stack
in
loop stack
end
implement
main0 () =
let
var nonlinear_stack : stack_t (int) = stack_t_nil ()
var linear_stack : stack_vt (int) = stack_vt_nil ()
implement stack_vt_free$element_free<int> x = begin end
overload is_empty with stack_t_is_empty
overload is_empty with stack_vt_is_empty
overload push with stack_t_push
overload push with stack_vt_push
overload pop with stack_t_pop
overload pop with stack_vt_pop
in
println! ("nonlinear_stack is empty? ", is_empty nonlinear_stack);
println! ("linear_stack is empty? ", is_empty linear_stack);
println! ("pushing 3, 2, 1...");
push (nonlinear_stack, 3);
push (nonlinear_stack, 2);
push (nonlinear_stack, 1);
push (linear_stack, 3);
push (linear_stack, 2);
push (linear_stack, 1);
println! ("nonlinear_stack is empty? ", is_empty nonlinear_stack);
println! ("linear_stack is empty? ", is_empty linear_stack);
println! ("popping nonlinear_stack: ", (pop nonlinear_stack) : int);
println! ("popping nonlinear_stack: ", (pop nonlinear_stack) : int);
println! ("popping nonlinear_stack: ", (pop nonlinear_stack) : int);
println! ("popping linear_stack: ", (pop linear_stack) : int);
println! ("popping linear_stack: ", (pop linear_stack) : int);
println! ("popping linear_stack: ", (pop linear_stack) : int);
println! ("nonlinear_stack is empty? ", is_empty nonlinear_stack);
println! ("linear_stack is empty? ", is_empty linear_stack);
stack_vt_free<int> linear_stack
end

62
Task/Stack/AWK/stack.awk Normal file
View file

@ -0,0 +1,62 @@
function deque(arr) {
arr["start"] = 0
arr["end"] = 0
}
function dequelen(arr) {
return arr["end"] - arr["start"]
}
function empty(arr) {
return dequelen(arr) == 0
}
function push(arr, elem) {
arr[++arr["end"]] = elem
}
function pop(arr) {
if (empty(arr)) {
return
}
return arr[arr["end"]--]
}
function unshift(arr, elem) {
arr[arr["start"]--] = elem
}
function shift(arr) {
if (empty(arr)) {
return
}
return arr[++arr["start"]]
}
function peek(arr) {
if (empty(arr)) {
return
}
return arr[arr["end"]]
}
function printdeque(arr, i, sep) {
printf("[")
for (i = arr["start"] + 1; i <= arr["end"]; i++) {
printf("%s%s", sep, arr[i])
sep = ", "
}
printf("]\n")
}
BEGIN {
deque(q)
for (i = 1; i <= 10; i++) {
push(q, i)
}
printdeque(q)
for (i = 1; i <= 10; i++) {
print pop(q)
}
printdeque(q)
}

View file

@ -0,0 +1,60 @@
DEFINE MAXSIZE="200"
BYTE ARRAY stack(MAXSIZE)
BYTE stacksize=[0]
BYTE FUNC IsEmpty()
IF stacksize=0 THEN
RETURN (1)
FI
RETURN (0)
PROC Push(BYTE v)
IF stacksize=maxsize THEN
PrintE("Error: stack is full!")
Break()
FI
stack(stacksize)=v
stacksize==+1
RETURN
BYTE FUNC Pop()
IF IsEmpty() THEN
PrintE("Error: stack is empty!")
Break()
FI
stacksize==-1
RETURN (stack(stacksize))
PROC TestIsEmpty()
IF IsEmpty() THEN
PrintE("Stack is empty")
ELSE
PrintE("Stack is not empty")
FI
RETURN
PROC TestPush(BYTE v)
PrintF("Push: %B%E",v)
Push(v)
RETURN
PROC TestPop()
BYTE v
Print("Pop: ")
v=Pop()
PrintBE(v)
RETURN
PROC Main()
TestIsEmpty()
TestPush(10)
TestIsEmpty()
TestPush(31)
TestPop()
TestIsEmpty()
TestPush(5)
TestPop()
TestPop()
TestPop()
RETURN

View file

@ -0,0 +1,78 @@
CARD EndProg ;required for ALLOCATE.ACT
INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program!
DEFINE PTR="CARD"
DEFINE NODE_SIZE="3"
TYPE StackNode=[BYTE data PTR nxt]
StackNode POINTER stack
BYTE FUNC IsEmpty()
IF stack=0 THEN
RETURN (1)
FI
RETURN (0)
PROC Push(BYTE v)
StackNode POINTER node
node=Alloc(NODE_SIZE)
node.data=v
node.nxt=stack
stack=node
RETURN
BYTE FUNC Pop()
StackNode POINTER node
BYTE v
IF IsEmpty() THEN
PrintE("Error stack is empty!")
Break()
FI
node=stack
v=node.data
stack=node.nxt
Free(node,NODE_SIZE)
RETURN (v)
PROC TestIsEmpty()
IF IsEmpty() THEN
PrintE("Stack is empty")
ELSE
PrintE("Stack is not empty")
FI
RETURN
PROC TestPush(BYTE v)
PrintF("Push: %B%E",v)
Push(v)
RETURN
PROC TestPop()
BYTE v
Print("Pop: ")
v=Pop()
PrintBE(v)
RETURN
PROC Main()
AllocInit(0)
stack=0
Put(125) PutE() ;clear screen
TestIsEmpty()
TestPush(10)
TestIsEmpty()
TestPush(31)
TestPop()
TestIsEmpty()
TestPush(5)
TestPop()
TestPop()
TestPop()
RETURN

View file

@ -0,0 +1,5 @@
var stack:Array = new Array();
stack.push(1);
stack.push(2);
trace(stack.pop()); // outputs "2"
trace(stack.pop()); // outputs "1"

View file

@ -0,0 +1,16 @@
generic
type Element_Type is private;
package Generic_Stack is
type Stack is private;
procedure Push (Item : Element_Type; Onto : in out Stack);
procedure Pop (Item : out Element_Type; From : in out Stack);
function Create return Stack;
Stack_Empty_Error : exception;
private
type Node;
type Stack is access Node;
type Node is record
Element : Element_Type;
Next : Stack := null;
end record;
end Generic_Stack;

View file

@ -0,0 +1,42 @@
with Ada.Unchecked_Deallocation;
package body Generic_Stack is
------------
-- Create --
------------
function Create return Stack is
begin
return (null);
end Create;
----------
-- Push --
----------
procedure Push(Item : Element_Type; Onto : in out Stack) is
Temp : Stack := new Node;
begin
Temp.Element := Item;
Temp.Next := Onto;
Onto := Temp;
end Push;
---------
-- Pop --
---------
procedure Pop(Item : out Element_Type; From : in out Stack) is
procedure Free is new Ada.Unchecked_Deallocation(Node, Stack);
Temp : Stack := From;
begin
if Temp = null then
raise Stack_Empty_Error;
end if;
Item := Temp.Element;
From := Temp.Next;
Free(Temp);
end Pop;
end Generic_Stack;

View file

@ -0,0 +1,39 @@
100 DIM STACK$(1000)
110 DATA "(2*A)","PI","","TO BE OR","NOT TO BE"
120 FOR I = 1 TO 5
130 READ ELEMENT$
140 GOSUB 500_PUSH
150 NEXT
200 GOSUB 400 POP AND PRINT
210 GOSUB 300_EMPTY AND PRINT
220 FOR I = 1 TO 4
230 GOSUB 400 POP AND PRINT
240 NEXT
250 GOSUB 300_EMPTY AND PRINT
260 END
300 GOSUB 700_EMPTY
310 PRINT "STACK IS ";
320 IF NOT EMPTY THEN PRINT "NOT ";
330 PRINT "EMPTY"
340 RETURN
400 GOSUB 600 POP
410 PRINT ELEMENT$
420 RETURN
500 REM
510 REM PUSH
520 REM
530 LET STACK$(SP) = ELEMENT$
540 LET SP = SP + 1
550 RETURN
600 REM
610 REM POP
620 REM
630 IF SP THEN SP = SP - 1
640 LET ELEMENT$ = STACK$(SP)
650 LET STACK$(SP) = ""
660 RETURN
700 REM
710 REM EMPTY
720 REM
730 LET EMPTY = SP = 0
740 RETURN

View file

@ -0,0 +1,23 @@
Stack: $[]-> []
pushTo: function [st val]-> 'st ++ val
popStack: function [st] [
result: last st
remove 'st .index (size st)-1
return result
]
emptyStack: function [st]-> empty 'st
printStack: function [st]-> print st
st: new Stack
pushTo st "one"
pushTo st "two"
pushTo st "three"
printStack st
print popStack st
printStack st
emptyStack st
print ["finally:" st]

View file

@ -0,0 +1,39 @@
msgbox % stack("push", 4)
msgbox % stack("push", 5)
msgbox % stack("peek")
msgbox % stack("pop")
msgbox % stack("peek")
msgbox % stack("empty")
msgbox % stack("pop")
msgbox % stack("empty")
return
stack(command, value = 0)
{
static
if !pointer
pointer = 10000
if (command = "push")
{
_p%pointer% := value
pointer -= 1
return value
}
if (command = "pop")
{
pointer += 1
return _p%pointer%
}
if (command = "peek")
{
next := pointer + 1
return _p%next%
}
if (command = "empty")
{
if (pointer == 10000)
return "empty"
else
return 0
}
}

14
Task/Stack/Axe/stack.axe Normal file
View file

@ -0,0 +1,14 @@
0→S
Lbl PUSH
r₁→{L₁+S}ʳ
S+2→S
Return
Lbl POP
S-2→S
{L₁+S}ʳ
Return
Lbl EMPTY
S≤≤0
Return

View file

@ -0,0 +1,31 @@
STACKSIZE = 1000
FOR n = 3 TO 5
PRINT "Push ";n : PROCpush(n)
NEXT
PRINT "Pop " ; FNpop
PRINT "Push 6" : PROCpush(6)
REPEAT
PRINT "Pop " ; FNpop
UNTIL FNisempty
PRINT "Pop " ; FNpop
END
DEF PROCpush(n) : LOCAL f%
DEF FNpop : LOCAL f% : f% = 1
DEF FNisempty : LOCAL f% : f% = 2
PRIVATE stack(), sptr%
DIM stack(STACKSIZE-1)
CASE f% OF
WHEN 0:
IF sptr% = DIM(stack(),1) ERROR 100, "Error: stack overflowed"
stack(sptr%) = n
sptr% += 1
WHEN 1:
IF sptr% = 0 ERROR 101, "Error: stack empty"
sptr% -= 1
= stack(sptr%)
WHEN 2:
= (sptr% = 0)
ENDCASE
ENDPROC

14
Task/Stack/BQN/stack.bqn Normal file
View file

@ -0,0 +1,14 @@
Push
Pop ¯1
¯1
Empty 0=
0=
123 Push 4
1 2 3 4
Pop 123
1 2
Empty 123
0
Empty
1

17
Task/Stack/Babel/stack.pb Normal file
View file

@ -0,0 +1,17 @@
main :
{ (1 2 3) foo set -- foo = (1 2 3)
4 foo push -- foo = (1 2 3 4)
0 foo unshift -- foo = (0 1 2 3 4)
foo pop -- foo = (0 1 2 3)
foo shift -- foo = (1 2 3)
check_foo
{ foo pop } 4 times -- Pops too many times, but this is OK and Babel won't complain
check_foo }
empty? : nil? -- just aliases 'empty?' to the built-in operator 'nil?'
check_foo! :
{ "foo is "
{foo empty?) {nil} {"not " .} ifte
"empty" .
cr << }

View file

@ -0,0 +1,69 @@
@echo off
setlocal enableDelayedExpansion
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: LIFO stack usage
:: Define the stack
call :newStack myStack
:: Push some values onto the stack
for %%A in (value1 value2 value3) do call :pushStack myStack %%A
:: Test if stack is empty by examining the top "attribute"
if myStack.top==0 (echo myStack is empty) else (echo myStack is NOT empty)
:: Peek at the top stack value
call:peekStack myStack val && echo a peek at the top of myStack shows !val!
:: Pop the top stack value
call :popStack myStack val && echo popped myStack value=!val!
:: Push some more values onto the stack
for %%A in (value4 value5 value6) do call :pushStack myStack %%A
:: Process the remainder of the stack
:processStack
call :popStack myStack val || goto :stackEmpty
echo popped myStack value=!val!
goto :processStack
:stackEmpty
:: Test if stack is empty using the empty "method"/"macro". Use of the
:: second IF statement serves to demonstrate the negation of the empty
:: "method". A single IF could have been used with an ELSE clause instead.
if %myStack.empty% echo myStack is empty
if not %myStack.empty% echo myStack is NOT empty
exit /b
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: LIFO stack definition
:newStack stackName
set /a %~1.top=0
:: Define an empty "method" for this stack as a sort of macro
set "%~1.empty=^!%~1.top^! == 0"
exit /b
:pushStack stackName value
set /a %~1.top+=1
set %~1.!%~1.top!=%2
exit /b
:popStack stackName returnVar
:: Sets errorlevel to 0 if success
:: Sets errorlevel to 1 if failure because stack was empty
if !%~1.top! equ 0 exit /b 1
for %%N in (!%~1.top!) do (
set %~2=!%~1.%%N!
set %~1.%%N=
)
set /a %~1.top-=1
exit /b 0
:peekStack stackName returnVar
:: Sets errorlevel to 0 if success
:: Sets errorlevel to 1 if failure because stack was empty
if !%~1.top! equ 0 exit /b 1
for %%N in (!%~1.top!) do set %~2=!%~1.%%N!
exit /b 0

View file

@ -0,0 +1,32 @@
( ( stack
= (S=)
(push=.(!arg.!(its.S)):?(its.S))
( pop
= top.!(its.S):(%?top.?(its.S))&!top
)
(top=top.!(its.S):(%?top.?)&!top)
(empty=.!(its.S):)
)
& new$stack:?Stack
& (Stack..push)$(2*a)
& (Stack..push)$pi
& (Stack..push)$
& (Stack..push)$"to be or"
& (Stack..push)$"not to be"
& out$((Stack..pop)$|"Cannot pop (a)")
& out$((Stack..top)$|"Cannot pop (b)")
& out$((Stack..pop)$|"Cannot pop (c)")
& out$((Stack..pop)$|"Cannot pop (d)")
& out$((Stack..pop)$|"Cannot pop (e)")
& out$((Stack..pop)$|"Cannot pop (f)")
& out$((Stack..pop)$|"Cannot pop (g)")
& out$((Stack..pop)$|"Cannot pop (h)")
& out
$ ( str
$ ( "Stack is "
((Stack..empty)$&|not)
" empty"
)
)
&
);

View file

@ -0,0 +1,6 @@
stack = []
stack.push 1
stack.push 2
stack.push 3
until { stack.empty? } { p stack.pop }

View file

@ -0,0 +1 @@
#include <stack>

View file

@ -0,0 +1,55 @@
#include <deque>
template <class T, class Sequence = std::deque<T> >
class stack {
friend bool operator== (const stack&, const stack&);
friend bool operator< (const stack&, const stack&);
public:
typedef typename Sequence::value_type value_type;
typedef typename Sequence::size_type size_type;
typedef Sequence container_type;
typedef typename Sequence::reference reference;
typedef typename Sequence::const_reference const_reference;
protected:
Sequence seq;
public:
stack() : seq() {}
explicit stack(const Sequence& s0) : seq(s0) {}
bool empty() const { return seq.empty(); }
size_type size() const { return seq.size(); }
reference top() { return seq.back(); }
const_reference top() const { return seq.back(); }
void push(const value_type& x) { seq.push_back(x); }
void pop() { seq.pop_back(); }
};
template <class T, class Sequence>
bool operator==(const stack<T,Sequence>& x, const stack<T,Sequence>& y)
{
return x.seq == y.seq;
}
template <class T, class Sequence>
bool operator<(const stack<T,Sequence>& x, const stack<T,Sequence>& y)
{
return x.seq < y.seq;
}
template <class T, class Sequence>
bool operator!=(const stack<T,Sequence>& x, const stack<T,Sequence>& y)
{
return !(x == y);
}
template <class T, class Sequence>
bool operator>(const stack<T,Sequence>& x, const stack<T,Sequence>& y)
{
return y < x;
}
template <class T, class Sequence>
bool operator<=(const stack<T,Sequence>& x, const stack<T,Sequence>& y)
{
return !(y < x);
}
template <class T, class Sequence>
bool operator>=(const stack<T,Sequence>& x, const stack<T,Sequence>& y)
{
return !(x < y);
}

View file

@ -0,0 +1,13 @@
// Non-Generic Stack
System.Collections.Stack stack = new System.Collections.Stack();
stack.Push( obj );
bool isEmpty = stack.Count == 0;
object top = stack.Peek(); // Peek without Popping.
top = stack.Pop();
// Generic Stack
System.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();
stack.Push(new Foo());
bool isEmpty = stack.Count == 0;
Foo top = stack.Peek(); // Peek without Popping.
top = stack.Pop();

62
Task/Stack/C/stack-1.c Normal file
View file

@ -0,0 +1,62 @@
#include <stdio.h>
#include <stdlib.h>
/* to read expanded code, run through cpp | indent -st */
#define DECL_STACK_TYPE(type, name) \
typedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name; \
stk_##name stk_##name##_create(size_t init_size) { \
stk_##name s; if (!init_size) init_size = 4; \
s = malloc(sizeof(struct stk_##name##_t)); \
if (!s) return 0; \
s->buf = malloc(sizeof(type) * init_size); \
if (!s->buf) { free(s); return 0; } \
s->len = 0, s->alloc = init_size; \
return s; } \
int stk_##name##_push(stk_##name s, type item) { \
type *tmp; \
if (s->len >= s->alloc) { \
tmp = realloc(s->buf, s->alloc*2*sizeof(type)); \
if (!tmp) return -1; s->buf = tmp; \
s->alloc *= 2; } \
s->buf[s->len++] = item; \
return s->len; } \
type stk_##name##_pop(stk_##name s) { \
type tmp; \
if (!s->len) abort(); \
tmp = s->buf[--s->len]; \
if (s->len * 2 <= s->alloc && s->alloc >= 8) { \
s->alloc /= 2; \
s->buf = realloc(s->buf, s->alloc * sizeof(type));} \
return tmp; } \
void stk_##name##_delete(stk_##name s) { \
free(s->buf); free(s); }
#define stk_empty(s) (!(s)->len)
#define stk_size(s) ((s)->len)
DECL_STACK_TYPE(int, int)
int main(void)
{
int i;
stk_int stk = stk_int_create(0);
printf("pushing: ");
for (i = 'a'; i <= 'z'; i++) {
printf(" %c", i);
stk_int_push(stk, i);
}
printf("\nsize now: %d", stk_size(stk));
printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not");
printf("\npoppoing:");
while (stk_size(stk))
printf(" %c", stk_int_pop(stk));
printf("\nsize now: %d", stk_size(stk));
printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not");
/* stk_int_pop(stk); <-- will abort() */
stk_int_delete(stk);
return 0;
}

71
Task/Stack/C/stack-2.c Normal file
View file

@ -0,0 +1,71 @@
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdbool.h>
#define check_pointer(p) if (!p) {puts("Out of memory."); exit(EXIT_FAILURE);}
#define MINIMUM_SIZE 1
/* Minimal stack size (expressed in number of elements) for which
space is allocated. It should be at least 1. */
#define GROWTH_FACTOR 2
/* How much more memory is allocated each time a stack grows
out of its allocated segment. */
typedef int T;
// The type of the stack elements.
typedef struct
{T *bottom;
T *top;
T *allocated_top;} stack;
stack * new(void)
/* Creates a new stack. */
{stack *s = malloc(sizeof(stack));
check_pointer(s);
s->bottom = malloc(MINIMUM_SIZE * sizeof(T));
check_pointer(s->bottom);
s->top = s->bottom - 1;
s->allocated_top = s->bottom + MINIMUM_SIZE - 1;
return s;}
void destroy(stack *s)
/* Frees all the memory used for a stack. */
{free(s->bottom);
free(s);}
bool empty(stack *s)
/* Returns true iff there are no elements on the stack. This
is different from the stack not having enough memory reserved
for even one element, which case is never allowed to arise. */
{return s->top < s->bottom ? true : false;}
void push(stack *s, T x)
/* Puts a new element on the stack, enlarging the latter's
memory allowance if necessary. */
{if (s->top == s->allocated_top)
{ptrdiff_t qtty = s->top - s->bottom + 1;
ptrdiff_t new_qtty = GROWTH_FACTOR * qtty;
s->bottom = realloc(s->bottom, new_qtty * sizeof(T));
check_pointer(s->bottom);
s->top = s->bottom + qtty - 1;
s->allocated_top = s->bottom + new_qtty - 1;}
*(++s->top) = x;}
T pop(stack *s)
/* Removes and returns the topmost element. The result of popping
an empty stack is undefined. */
{return *(s->top--);}
void compress(stack *s)
/* Frees any memory the stack isn't actually using. The
allocated portion still isn't allowed to shrink smaller than
MINIMUM_SIZE. If all the stack's memory is in use, nothing
happens. */
{if (s->top == s->allocated_top) return;
ptrdiff_t qtty = s->top - s->bottom + 1;
if (qtty < MINIMUM_SIZE) qtty = MINIMUM_SIZE;
size_t new_size = qtty * sizeof(T);
s->bottom = realloc(s->bottom, new_size);
check_pointer(s->bottom);
s->allocated_top = s->bottom + qtty - 1;}

55
Task/Stack/CLU/stack.clu Normal file
View file

@ -0,0 +1,55 @@
% Stack
stack = cluster [T: type] is new, push, pop, peek, empty
rep = array[T]
new = proc () returns (cvt)
return (rep$new())
end new
empty = proc (s: cvt) returns (bool)
return (rep$size(s) = 0)
end empty;
push = proc (s: cvt, val: T)
rep$addh(s, val)
end push;
pop = proc (s: cvt) returns (T) signals (empty)
if rep$empty(s)
then signal empty
else return(rep$remh(s))
end
end pop
peek = proc (s: cvt) returns (T) signals (empty)
if rep$empty(s)
then signal empty
else return(s[rep$high(s)])
end
end peek
end stack
start_up = proc ()
po: stream := stream$primary_output()
% Make a stack
s: stack[int] := stack[int]$new()
% Push 1..10 onto the stack
for i: int in int$from_to(1, 10) do
stack[int]$push(s, i)
end
% Pop items off the stack until the stack is empty
while ~stack[int]$empty(s) do
stream$putl(po, int$unparse(stack[int]$pop(s)))
end
% Trying to pop off the stack now should raise 'empty'
begin
i: int := stack[int]$pop(s)
stream$putl(po, "Still here! And I got: " || int$unparse(i))
end except when empty:
stream$putl(po, "The stack is empty.")
end
end start_up

View file

@ -0,0 +1,2 @@
01 stack.
05 head USAGE IS POINTER VALUE NULL.

View file

@ -0,0 +1,5 @@
01 node BASED.
COPY node-info REPLACING
01 BY 05
node-info BY info.
05 link USAGE IS POINTER VALUE NULL.

View file

@ -0,0 +1 @@
01 node-info PICTURE X(10) VALUE SPACES.

View file

@ -0,0 +1,3 @@
01 p PICTURE 9.
88 nil VALUE ZERO WHEN SET TO FALSE IS 1.
88 t VALUE 1 WHEN SET TO FALSE IS ZERO.

View file

@ -0,0 +1,247 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. push.
DATA DIVISION.
LOCAL-STORAGE SECTION.
COPY p.
COPY node.
LINKAGE SECTION.
COPY stack.
01 node-info-any PICTURE X ANY LENGTH.
PROCEDURE DIVISION USING stack node-info-any.
ALLOCATE node
CALL "pointerp" USING
BY REFERENCE ADDRESS OF node
BY REFERENCE p
END-CALL
IF nil
CALL "stack-overflow-error" END-CALL
ELSE
MOVE node-info-any TO info OF node
SET link OF node TO head OF stack
SET head OF stack TO ADDRESS OF node
END-IF
GOBACK.
END PROGRAM push.
IDENTIFICATION DIVISION.
PROGRAM-ID. pop.
DATA DIVISION.
LOCAL-STORAGE SECTION.
COPY p.
COPY node.
LINKAGE SECTION.
COPY stack.
COPY node-info.
PROCEDURE DIVISION USING stack node-info.
CALL "empty" USING
BY REFERENCE stack
BY REFERENCE p
END-CALL
IF t
CALL "stack-underflow-error" END-CALL
ELSE
SET ADDRESS OF node TO head OF stack
SET head OF stack TO link OF node
MOVE info OF node TO node-info
END-IF
FREE ADDRESS OF node
GOBACK.
END PROGRAM pop.
IDENTIFICATION DIVISION.
PROGRAM-ID. empty.
DATA DIVISION.
LOCAL-STORAGE SECTION.
LINKAGE SECTION.
COPY stack.
COPY p.
PROCEDURE DIVISION USING stack p.
CALL "pointerp" USING
BY CONTENT head OF stack
BY REFERENCE p
END-CALL
IF t
SET t TO FALSE
ELSE
SET t TO TRUE
END-IF
GOBACK.
END PROGRAM empty.
IDENTIFICATION DIVISION.
PROGRAM-ID. head.
DATA DIVISION.
LOCAL-STORAGE SECTION.
COPY p.
COPY node.
LINKAGE SECTION.
COPY stack.
COPY node-info.
PROCEDURE DIVISION USING stack node-info.
CALL "empty" USING
BY REFERENCE stack
BY REFERENCE p
END-CALL
IF t
CALL "stack-underflow-error" END-CALL
ELSE
SET ADDRESS OF node TO head OF stack
MOVE info OF node TO node-info
END-IF
GOBACK.
END PROGRAM head.
IDENTIFICATION DIVISION.
PROGRAM-ID. peek.
DATA DIVISION.
LOCAL-STORAGE SECTION.
LINKAGE SECTION.
COPY stack.
COPY node-info.
PROCEDURE DIVISION USING stack node-info.
CALL "head" USING
BY CONTENT stack
BY REFERENCE node-info
END-CALL
GOBACK.
END PROGRAM peek.
IDENTIFICATION DIVISION.
PROGRAM-ID. pointerp.
DATA DIVISION.
LINKAGE SECTION.
01 test-pointer USAGE IS POINTER.
COPY p.
PROCEDURE DIVISION USING test-pointer p.
IF test-pointer EQUAL NULL
SET nil TO TRUE
ELSE
SET t TO TRUE
END-IF
GOBACK.
END PROGRAM pointerp.
IDENTIFICATION DIVISION.
PROGRAM-ID. stack-overflow-error.
PROCEDURE DIVISION.
DISPLAY "stack-overflow-error" END-DISPLAY
STOP RUN.
END PROGRAM stack-overflow-error.
IDENTIFICATION DIVISION.
PROGRAM-ID. stack-underflow-error.
PROCEDURE DIVISION.
DISPLAY "stack-underflow-error" END-DISPLAY
STOP RUN.
END PROGRAM stack-underflow-error.
IDENTIFICATION DIVISION.
PROGRAM-ID. copy-stack.
DATA DIVISION.
LOCAL-STORAGE SECTION.
COPY p.
COPY node-info.
LINKAGE SECTION.
COPY stack.
COPY stack REPLACING stack BY new-stack.
PROCEDURE DIVISION USING stack new-stack.
CALL "empty" USING
BY REFERENCE stack
BY REFERENCE p
END-CALL
IF nil
CALL "pop" USING
BY REFERENCE stack
BY REFERENCE node-info
END-CALL
CALL "copy-stack" USING
BY REFERENCE stack
BY REFERENCE new-stack
END-CALL
CALL "push" USING
BY REFERENCE stack
BY REFERENCE node-info
END-CALL
CALL "push" USING
BY REFERENCE new-stack
BY REFERENCE node-info
END-CALL
END-IF
GOBACK.
END PROGRAM copy-stack.
IDENTIFICATION DIVISION.
PROGRAM-ID. reverse-stack.
DATA DIVISION.
LOCAL-STORAGE SECTION.
COPY p.
COPY node-info.
LINKAGE SECTION.
COPY stack.
COPY stack REPLACING stack BY new-stack.
PROCEDURE DIVISION USING stack new-stack.
CALL "empty" USING
BY REFERENCE stack
BY REFERENCE p
END-CALL
IF nil
CALL "pop" USING
BY REFERENCE stack
BY REFERENCE node-info
END-CALL
CALL "push" USING
BY REFERENCE new-stack
BY REFERENCE node-info
END-CALL
CALL "reverse-stack" USING
BY REFERENCE stack
BY REFERENCE new-stack
END-CALL
CALL "push" USING
BY REFERENCE stack
BY REFERENCE node-info
END-CALL
END-IF
GOBACK.
END PROGRAM reverse-stack.
IDENTIFICATION DIVISION.
PROGRAM-ID. traverse-stack.
DATA DIVISION.
LOCAL-STORAGE SECTION.
COPY p.
COPY node-info.
COPY stack REPLACING stack BY new-stack.
LINKAGE SECTION.
COPY stack.
PROCEDURE DIVISION USING stack.
CALL "copy-stack" USING
BY REFERENCE stack
BY REFERENCE new-stack
END-CALL
CALL "empty" USING
BY REFERENCE new-stack
BY REFERENCE p
END-CALL
IF nil
CALL "head" USING
BY CONTENT new-stack
BY REFERENCE node-info
END-CALL
DISPLAY node-info END-DISPLAY
CALL "peek" USING
BY CONTENT new-stack
BY REFERENCE node-info
END-CALL
DISPLAY node-info END-DISPLAY
CALL "pop" USING
BY REFERENCE new-stack
BY REFERENCE node-info
END-CALL
DISPLAY node-info END-DISPLAY
CALL "traverse-stack" USING
BY REFERENCE new-stack
END-CALL
END-IF
GOBACK.
END PROGRAM traverse-stack.

View file

@ -0,0 +1,37 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. stack-test.
DATA DIVISION.
LOCAL-STORAGE SECTION.
COPY stack.
COPY stack REPLACING stack BY new-stack.
PROCEDURE DIVISION.
CALL "push" USING
BY REFERENCE stack
BY CONTENT "daleth"
END-CALL
CALL "push" USING
BY REFERENCE stack
BY CONTENT "gimel"
END-CALL
CALL "push" USING
BY REFERENCE stack
BY CONTENT "beth"
END-CALL
CALL "push" USING
BY REFERENCE stack
BY CONTENT "aleph"
END-CALL
CALL "traverse-stack" USING
BY REFERENCE stack
END-CALL
CALL "reverse-stack" USING
BY REFERENCE stack
BY REFERENCE new-stack
END-CALL
CALL "traverse-stack" USING
BY REFERENCE new-stack
END-CALL
STOP RUN.
END PROGRAM stack-test.
COPY stack-utilities.

View file

@ -0,0 +1,20 @@
(deftype Stack [elements])
(def stack (Stack (ref ())))
(defn push-stack
"Pushes an item to the top of the stack."
[x] (dosync (alter (:elements stack) conj x)))
(defn pop-stack
"Pops an item from the top of the stack."
[] (let [fst (first (deref (:elements stack)))]
(dosync (alter (:elements stack) rest)) fst))
(defn top-stack
"Shows what's on the top of the stack."
[] (first (deref (:elements stack))))
(defn empty-stack?
"Tests whether or not the stack is empty."
[] (= () (deref (:elements stack))))

View file

@ -0,0 +1,14 @@
(defprotocol StackOps
(push-stack [this x] "Pushes an item to the top of the stack.")
(pop-stack [this] "Pops an item from the top of the stack.")
(top-stack [this] "Shows what's on the top of the stack.")
(empty-stack? [this] "Tests whether or not the stack is empty."))
(deftype Stack [elements]
StackOps
(push-stack [x] (dosync (alter elements conj x)))
(pop-stack [] (let [fst (first (deref elements))]
(dosync (alter elements rest)) fst))
(top-stack [] (first (deref elements)))
(empty-stack? [] (= () (deref elements))))
(def stack (Stack (ref ())))

View file

@ -0,0 +1,6 @@
stack = []
stack.push 1
stack.push 2
console.log stack
console.log stack.pop()
console.log stack

View file

@ -0,0 +1,16 @@
(defstruct stack
elements)
(defun stack-push (element stack)
(push element (stack-elements stack)))
(defun stack-pop (stack)(deftype Stack [elements])
(defun stack-empty (stack)
(endp (stack-elements stack)))
(defun stack-top (stack)
(first (stack-elements stack)))
(defun stack-peek (stack)
(stack-top stack))

View file

@ -0,0 +1,110 @@
MODULE Stacks;
IMPORT StdLog;
TYPE
(* some pointers to records *)
Object* = POINTER TO ABSTRACT RECORD END;
Integer = POINTER TO RECORD (Object)
i: INTEGER
END;
Point = POINTER TO RECORD (Object)
x,y: REAL
END;
Node = POINTER TO LIMITED RECORD
next- : Node;
data-: ANYPTR;
END;
(* Stack *)
Stack* = POINTER TO RECORD
top- : Node;
END;
PROCEDURE (dn: Object) Show*, NEW, ABSTRACT;
PROCEDURE (i: Integer) Show*;
BEGIN
StdLog.String("Integer(");StdLog.Int(i.i);StdLog.String(");");StdLog.Ln
END Show;
PROCEDURE (p: Point) Show*;
BEGIN
StdLog.String("Point(");StdLog.Real(p.x);StdLog.Char(',');
StdLog.Real(p.y);StdLog.String(");");StdLog.Ln
END Show;
PROCEDURE (s: Stack) Init, NEW;
BEGIN
s.top := NIL;
END Init;
PROCEDURE (s: Stack) Push*(data: ANYPTR), NEW;
VAR
n: Node;
BEGIN
NEW(n);n.next := NIL;n.data := data;
IF s.top = NIL THEN
s.top := n
ELSE
n.next := s.top;
s.top := n
END
END Push;
PROCEDURE (s: Stack) Pop*(): ANYPTR, NEW;
VAR
x: ANYPTR;
BEGIN
IF s.top # NIL THEN
x := s.top.data;
s.top := s.top.next
ELSE
x := NIL
END;
RETURN x
END Pop;
PROCEDURE (s: Stack) Empty*(): BOOLEAN, NEW;
BEGIN
RETURN s.top = NIL
END Empty;
PROCEDURE NewStack*(): Stack;
VAR
s: Stack;
BEGIN
NEW(s);s.Init;
RETURN s
END NewStack;
PROCEDURE NewInteger*(data: INTEGER): Integer;
VAR
i: Integer;
BEGIN
NEW(i);i.i := data;
RETURN i
END NewInteger;
PROCEDURE NewPoint*(x,y: REAL): Point;
VAR
p: Point;
BEGIN
NEW(p);p.x := x;p.y := y;
RETURN p
END NewPoint;
PROCEDURE TestStack*;
VAR
s: Stack;
BEGIN
s := NewStack();
s.Push(NewInteger(1));
s.Push(NewPoint(2.0,3.4));
s.Pop()(Object).Show();
s.Pop()(Object).Show();
END TestStack;
END Stacks.

View file

@ -0,0 +1,8 @@
stack = [] of Int32
(1..10).each do |x|
stack.push x
end
10.times do
puts stack.pop
end

26
Task/Stack/D/stack.d Normal file
View file

@ -0,0 +1,26 @@
import std.array;
class Stack(T) {
private T[] items;
@property bool empty() { return items.empty(); }
void push(T top) { items ~= top; }
T pop() {
if (this.empty)
throw new Exception("Empty Stack.");
auto top = items.back;
items.popBack();
return top;
}
}
void main() {
auto s = new Stack!int();
s.push(10);
s.push(20);
assert(s.pop() == 20);
assert(s.pop() == 10);
assert(s.empty());
}

View file

@ -0,0 +1,11 @@
var stack: array of Integer;
stack.Push(1);
stack.Push(2);
stack.Push(3);
PrintLn(stack.Pop); // 3
PrintLn(stack.Pop); // 2
PrintLn(stack.Pop); // 1
Assert(stack.Length = 0); // assert empty

View file

@ -0,0 +1,24 @@
program Stack;
{$APPTYPE CONSOLE}
uses Generics.Collections;
var
lStack: TStack<Integer>;
begin
lStack := TStack<Integer>.Create;
try
lStack.Push(1);
lStack.Push(2);
lStack.Push(3);
Assert(lStack.Peek = 3); // 3 should be at the top of the stack
Writeln(lStack.Pop); // 3
Writeln(lStack.Pop); // 2
Writeln(lStack.Pop); // 1
Assert(lStack.Count = 0); // should be empty
finally
lStack.Free;
end;
end.

View file

@ -0,0 +1,26 @@
set_ns(rosettacode)_me();
add_stack({int},a)_values(1..4); // 1,2,3,4 (1 is first/bottom, 4 is last/top)
with_stack(a)_pop(); // 1,2,3
with_stack(a)_push()_v(5,6); // 1,2,3,5,6
add_var({int},b)_value(7);
with_stack(a)_push[b]; // 1,2,3,5,6,7
with_stack(a)_pluck()_at(2); // callee will return `with_stack(a)_err(pluck invalid with stack);`
me_msg()_stack(a)_top(); // "7"
me_msg()_stack(a)_last(); // "7"
me_msg()_stack(a)_peek(); // "7"
me_msg()_stack(a)_bottom(); // "1"
me_msg()_stack(a)_first(); // "1"
me_msg()_stack(a)_peer(); // "1"
me_msg()_stack(a)_isempty(); // "false"
with_stack(a)_empty();
with_stack(a)_msg()_isempty()_me(); // "true" (alternative syntax)
me_msg()_stack(a)_history()_all(); // returns th entire history of stack 'a' since its creation
reset_ns[];

View file

@ -0,0 +1,23 @@
type Stack() {
var xs = []
}
func Stack.IsEmpty() => this!xs.Length() == 0
func Stack.Peek() => this!xs[this!xs.Length() - 1]
func Stack.Pop() {
var e = this!xs[this!xs.Length() - 1]
this!xs.RemoveAt(this!xs.Length() - 1)
return e
}
func Stack.Push(item) => this!xs.Add(item)
var stack = Stack()
stack.Push(1)
stack.Push(2)
print(stack.Pop())
print(stack.Peek())
stack.Pop()
print(stack.IsEmpty())

22
Task/Stack/E/stack-1.e Normal file
View file

@ -0,0 +1,22 @@
? def l := [].diverge()
# value: [].diverge()
? l.push(1)
? l.push(2)
? l
# value: [1, 2].diverge()
? l.pop()
# value: 2
? l.size().aboveZero()
# value: true
? l.last()
# value: 1
? l.pop()
# value: 1
? l.size().aboveZero()
# value: false

30
Task/Stack/E/stack-2.e Normal file
View file

@ -0,0 +1,30 @@
def makeStack() {
var store := null
def stack {
to push(x) { store := [x, store] }
to pop() { def [x, next] := store; store := next; return x }
to last() { return store[0] }
to empty() { return (store == null) }
}
return stack
}
? def s := makeStack()
# value: <stack>
? s.push(1)
? s.push(2)
? s.last()
# value: 2
? s.pop()
# value: 2
? s.empty()
# value: false
? s.pop()
# value: 1
? s.empty()
# value: true

View file

@ -0,0 +1,20 @@
; build stack [0 1 ... 9 (top)] from a list
(list->stack (iota 10) 'my-stack)
(stack-top 'my-stack) → 9
(pop 'my-stack) → 9
(stack-top 'my-stack) → 8
(push 'my-stack '🐸) ; any kind of lisp object in the stack
(stack-empty? 'my-stack) → #f
(stack->list 'my-stack) ; convert stack to list
→ (0 1 2 3 4 5 6 7 8 🐸)
(stack-swap 'my-stack) ; swaps two last items
→ 8 ; new top
(stack->list 'my-stack)
→ (0 1 2 3 4 5 6 7 🐸 8) ; swapped
(while (not (stack-empty? 'my-stack)) (pop 'my-stack)) ; pop until empty
(stack-empty? 'my-stack) → #t ; true
(push 'my-stack 7)
my-stack ; a stack is not a variable, nor a symbol - cannot be evaluated
⛔ error: #|user| : unbound variable : my-stack
(stack-top 'my-stack) → 7

43
Task/Stack/Eiffel/stack.e Normal file
View file

@ -0,0 +1,43 @@
class
STACK_ON_ARRAY
create
make
feature -- Implementation
empty: BOOLEAN
do
Result := stack.is_empty
ensure
empty: Result = (stack.count = 0)
end
push (item: ANY)
do
stack.force (item, stack.count)
ensure
pushed: stack [stack.upper] = item
growth: stack.count = old stack.count + 1
end
pop: ANY
require
not_empty: not empty
do
Result := stack.at (stack.upper)
stack.remove_tail (1)
ensure
reduction: stack.count = old stack.count - 1
end
feature {NONE} -- Initialization
stack: ARRAY [ANY]
make
do
create stack.make_empty
end
end

View file

@ -0,0 +1,12 @@
public program()
{
var stack := new system'collections'Stack();
stack.push:2;
var isEmpty := stack.Length == 0;
var item := stack.peek(); // Peek without Popping.
item := stack.pop()
}

View file

@ -0,0 +1,21 @@
component GenericStack ( Stack, Element );
type Stack;
Stack (MaxSize = integer) -> Stack;
Empty ( Stack ) -> boolean;
Full ( Stack ) -> boolean;
Push ( Stack, Element) -> nothing;
Pull ( Stack ) -> Element;
begin
Stack(MaxSize) =
Stack:[ MaxSize; index:=0; area=array (Element, MaxSize) ];
Empty( stack ) = (stack.index <= 0);
Full ( stack ) = (stack.index >= stack.MaxSize);
Push ( stack, element ) =
[ exception (Full (stack), "Stack Overflow");
stack.index:=stack.index + 1;
stack.area[stack.index]:=element ];
Pull ( stack ) =
[ exception (Empty (stack), "Stack Underflow");
stack.index:=stack.index - 1;
stack.area[stack.index + 1] ];
end component GenericStack;

View file

@ -0,0 +1,25 @@
component GenericStack ( Stack, ElementType );
type Stack;
Stack(MaxSize = integer) -> Stack;
Empty( Stack ) -> boolean;
Full ( Stack ) -> boolean;
Push ( Stack, ElementType)-> nothing;
Pull ( Stack ) -> ElementType;
begin
type sequence = term;
ElementType & sequence => sequence;
nil = null (sequence);
head (sequence) -> ElementType;
head (X & Y) = ElementType:X;
tail (sequence) -> sequence;
tail (X & Y) = Y;
Stack (Size) = Stack:[ list = nil ];
Empty ( stack ) = (stack.list == nil);
Full ( stack ) = false;
Push ( stack, ElementType ) = [ stack.list:= ElementType & stack.list ];
Pull ( stack ) = [ exception (Empty (stack), "Stack Underflow");
Head = head(stack.list); stack.list:=tail(stack.list); Head];
end component GenericStack;

View file

@ -0,0 +1,15 @@
use GenericStack (StackofBooks, Book);
type Book = text;
BookStack = StackofBooks(50);
Push (BookStack, "Peter Pan");
Push (BookStack, "Alice in Wonderland");
Pull (BookStack)?
"Alice in Wonderland"
Pull (BookStack)?
"Peter Pan"
Pull (BookStack)?
***** Exception: Stack Underflow

View file

@ -0,0 +1,12 @@
defmodule Stack do
def new, do: []
def empty?([]), do: true
def empty?(_), do: false
def pop([h|t]), do: {h,t}
def push(h,t), do: [h|t]
def top([h|_]), do: h
end

View file

@ -0,0 +1,13 @@
-module(stack).
-export([empty/1, new/0, pop/1, push/2, top/1]).
new() -> [].
empty([]) -> true;
empty(_) -> false.
pop([H|T]) -> {H,T}.
push(H,T) -> [H|T].
top([H|_]) -> H.

View file

@ -0,0 +1,14 @@
1> c(stack).
{ok,stack}
2> Stack = stack:new().
[]
3> NewStack = lists:foldl(fun stack:push/2, Stack, [1,2,3,4,5]).
[5,4,3,2,1]
4> stack:top(NewStack).
5
5> {Popped, PoppedStack} = stack:pop(NewStack).
{5,[4,3,2,1]}
6> stack:empty(NewStack).
false
7> stack:empty(stack:new()).
true

View file

@ -0,0 +1,20 @@
type Stack<'a> //'//(workaround for syntax highlighting problem)
(?items) =
let items = defaultArg items []
member x.Push(A) = Stack(A::items)
member x.Pop() =
match items with
| x::xr -> (x, Stack(xr))
| [] -> failwith "Stack is empty."
member x.IsEmpty() = items = []
// example usage
let anEmptyStack = Stack<int>()
let stack2 = anEmptyStack.Push(42)
printfn "%A" (stack2.IsEmpty())
let (x, stack3) = stack2.Pop()
printfn "%d" x
printfn "%A" (stack3.IsEmpty())

View file

@ -0,0 +1,12 @@
V{ 1 2 3 } {
[ 6 swap push ]
[ "hi" swap push ]
[ "Vector is now: " write . ]
[ "Let's pop it: " write pop . ]
[ "Vector is now: " write . ]
[ "Top is: " write last . ] } cleave
Vector is now: V{ 1 2 3 6 "hi" }
Let's pop it: "hi"
Vector is now: V{ 1 2 3 6 }
Top is: 6

View file

@ -0,0 +1,15 @@
: stack ( size -- )
create here cell+ , cells allot ;
: push ( n st -- ) tuck @ ! cell swap +! ;
: pop ( st -- n ) -cell over +! @ @ ;
: empty? ( st -- ? ) dup @ - cell+ 0= ;
10 stack st
1 st push
2 st push
3 st push
st empty? . \ 0 (false)
st pop . st pop . st pop . \ 3 2 1
st empty? . \ -1 (true)

111
Task/Stack/Fortran/stack.f Normal file
View file

@ -0,0 +1,111 @@
module mod_stack
implicit none
type node
! data entry in each node
real*8, private :: data
! pointer to the next node of the linked list
type(node), pointer, private :: next
end type node
private node
type stack
! pointer to first element of stack.
type(node), pointer, private :: first
! size of stack
integer, private :: len=0
contains
procedure :: pop
procedure :: push
procedure :: peek
procedure :: getSize
procedure :: clearStack
procedure :: isEmpty
end type stack
contains
function pop(this) result(x)
class(stack) :: this
real*8 :: x
type(node), pointer :: tmp
if ( this%len == 0 ) then
print*, "popping from empty stack"
!stop
end if
tmp => this%first
x = this%first%data
this%first => this%first%next
deallocate(tmp)
this%len = this%len -1
end function pop
subroutine push(this, x)
real*8 :: x
class(stack), target :: this
type(node), pointer :: new, tmp
allocate(new)
new%data = x
if (.not. associated(this%first)) then
this%first => new
else
tmp => this%first
this%first => new
this%first%next => tmp
end if
this%len = this%len + 1
end subroutine push
function peek(this) result(x)
class(stack) :: this
real*8 :: x
x = this%first%data
end function peek
function getSize(this) result(n)
class(stack) :: this
integer :: n
n = this%len
end function getSize
function isEmpty(this) result(empty)
class(stack) :: this
logical :: empty
if ( this%len > 0 ) then
empty = .FALSE.
else
empty = .TRUE.
end if
end function isEmpty
subroutine clearStack(this)
class(stack) :: this
type(node), pointer :: tmp
integer :: i
if ( this%len == 0 ) then
return
end if
do i = 1, this%len
tmp => this%first
if ( .not. associated(tmp)) exit
this%first => this%first%next
deallocate(tmp)
end do
this%len = 0
end subroutine clearStack
end module mod_stack
program main
use mod_stack
type(stack) :: my_stack
integer :: i
real*8 :: dat
do i = 1, 5, 1
dat = 1.0 * i
call my_stack%push(dat)
end do
do while ( .not. my_stack%isEmpty() )
print*, my_stack%pop()
end do
call my_stack%clearStack()
end program main

View file

@ -0,0 +1,23 @@
program Stack;
{$IFDEF FPC}{$MODE DELPHI}{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF}{$ENDIF}
{$ASSERTIONS ON}
uses Generics.Collections;
var
lStack: TStack<Integer>;
begin
lStack := TStack<Integer>.Create;
try
lStack.Push(1);
lStack.Push(2);
lStack.Push(3);
Assert(lStack.Peek = 3); // 3 should be at the top of the stack
Write(lStack.Pop:2); // 3
Write(lStack.Pop:2); // 2
Writeln(lStack.Pop:2); // 1
Assert(lStack.Count = 0, 'Stack is not empty'); // should be empty
finally
lStack.Free;
end;
end.

View file

@ -0,0 +1,159 @@
PROGRAM StackObject.pas;
{$IFDEF FPC}
{$mode objfpc}{$H+}{$J-}{$m+}{$R+}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
(*)
Free Pascal Compiler version 3.2.0 [2020/06/14] for x86_64
TheStack free and readable alternative at C/C++ Sidxeeds
compiles natively to almost any platform, including raSidxberry PI *
Can run independently from DELPHI / Lazarus
For debian Linux: apt -y install fpc
It contains a text IDE called fp
This is an experiment for a stack that can handle almost any
simple type of variable.
What happens after retrieving the variable is TBD by you.
https://www.freepascal.org/advantage.var
(*)
USES
Classes ,
Crt ,
Variants ;
{$WARN 6058 off : Call to subroutine "$1" marked as inline is not inlined} // Use for variants
TYPE
Stack = OBJECT
CONST
CrLf = #13#10 ;
TYPE
VariantArr = array of variant ;
PRIVATE
Ar : VariantArr ;
{$MACRO ON}
{$DEFINE STACKSIZE := Length ( Ar ) * Ord ( Length ( Ar ) > 0 ) }
{$DEFINE TOP := STACKSIZE - 1 * Ord ( STACKSIZE > 0 ) }
{$DEFINE SLEN := length ( Ar [ TOP ] ) * Ord ( Length ( Ar [ TOP ] ) > 0 ) }
FUNCTION IsEmpty : boolean ;
PROCEDURE Print ;
FUNCTION Pop : variant ;
FUNCTION Peep : variant ;
PROCEDURE Push ( item : variant ) ;
FUNCTION SecPop : variant ;
PUBLIC
CONSTRUCTOR Create ;
END;
CONSTRUCTOR Stack.Create ;
BEGIN
SetLength ( Ar, STACKSIZE ) ;
END;
FUNCTION Stack.IsEmpty : boolean ;
BEGIN
IsEmpty := ( STACKSIZE < 1 ) ;
END;
PROCEDURE Stack.Print ;
VAR
i : shortint ;
BEGIN
IF ( TOP < 1 ) or ( IsEmpty ) THEN
BEGIN
WriteLn ( CrLf + '<empty stack>' ) ;
EXIT ;
END;
WriteLn ( CrLf , '<top>') ;
FOR i := ( TOP ) DOWNTO 0 DO WriteLn ( Ar [ i ] ) ;
WriteLn ( '<bottom>' ) ;
END;
FUNCTION Stack.Pop : variant ;
BEGIN
IF IsEmpty THEN EXIT ;
Pop := Ar [ TOP ] ;
SetLength ( Ar, TOP ) ;
END;
FUNCTION Stack.Peep : variant ;
BEGIN
IF IsEmpty THEN EXIT ;
Peep := Ar [ TOP ] ;
END;
PROCEDURE Stack.Push ( item : variant ) ;
BEGIN
SetLength ( Ar, STACKSIZE + 1 ) ;
Ar [ TOP ] := item ;
END;
FUNCTION Stack.SecPop : variant ;
(*) Pop and Wipe (*)
BEGIN
IF IsEmpty THEN EXIT ;
SecPop := Ar [ TOP ] ;
Ar [ TOP ] := StringOfChar ( #255 , SLEN ) ;
Ar [ TOP ] := StringOfChar ( #0 , SLEN ) ;
SetLength ( Ar, TOP ) ;
END;
VAR
n : integer ;
r : real ;
S : string ;
So : Stack ;
BEGIN
So.Create ;
So.Print ;
n := 23 ;
So.Push ( n ) ;
S := '3 guesses ' ;
So.Push ( S ) ;
r := 1.23 ;
So.Push ( r ) ;
WriteLn ( 'Peep : ', So.Peep ) ;
So.Push ( 'Nice Try' ) ;
So.Print ;
WriteLn ;
WriteLn ( 'SecPop : ',So.SecPop ) ;
WriteLn ( 'SecPop : ',So.SecPop ) ;
WriteLn ( 'SecPop : ',So.SecPop ) ;
WriteLn ( 'SecPop : ',So.SecPop ) ;
So.Print ;
END.

View file

@ -0,0 +1,85 @@
' FB 1.05.0 Win64
' stack_rosetta.bi
' simple generic Stack type
#Define Stack(T) Stack_##T
#Macro Declare_Stack(T)
Type Stack(T)
Public:
Declare Constructor()
Declare Destructor()
Declare Property capacity As Integer
Declare Property count As Integer
Declare Property empty As Boolean
Declare Property top As T
Declare Function pop() As T
Declare Sub push(item As T)
Private:
a(any) As T
count_ As Integer = 0
Declare Function resize(size As Integer) As Integer
End Type
Constructor Stack(T)()
Redim a(0 To 0) '' create a default T instance for various purposes
End Constructor
Destructor Stack(T)()
Erase a
End Destructor
Property Stack(T).capacity As Integer
Return UBound(a)
End Property
Property Stack(T).count As Integer
Return count_
End Property
Property Stack(T).empty As Boolean
Return count_ = 0
End Property
Property Stack(T).top As T
If count_ > 0 Then
Return a(count_)
End If
Print "Error: Attempted to access 'top' element of an empty stack"
Return a(0) '' return default element
End Property
Function Stack(T).pop() As T
If count_ > 0 Then
Dim value As T = a(count_)
a(count_) = a(0) '' zero element to be removed
count_ -= 1
Return value
End If
Print "Error: Attempted to remove 'top' element of an empty stack"
Return a(0) '' return default element
End Function
Sub Stack(T).push(item As T)
Dim size As Integer = UBound(a)
count_ += 1
If count_ > size Then
size = resize(size)
Redim Preserve a(0 to size)
End If
a(count_) = item
End Sub
Function Stack(T).resize(size As Integer) As Integer
If size = 0 Then
size = 4
ElseIf size <= 32 Then
size = 2 * size
Else
size += 32
End If
Return size
End Function
#EndMacro

View file

@ -0,0 +1,49 @@
' FB 1.05.0 Win64
#Include "stack_rosetta.bi"
Type Dog
name As String
age As Integer
Declare Constructor
Declare Constructor(name_ As string, age_ As integer)
Declare Operator Cast() As String
end type
Constructor Dog '' default constructor
End Constructor
Constructor Dog(name_ As String, age_ As Integer)
name = name_
age = age_
End Constructor
Operator Dog.Cast() As String
Return "[" + name + ", " + Str(age) + "]"
End Operator
Declare_Stack(Dog) '' expand Stack type for Dog instances
Dim dogStack As Stack(Dog)
Var cerberus = Dog("Cerberus", 10)
Var rover = Dog("Rover", 3)
Var puppy = Dog("Puppy", 0)
With dogStack '' push these Dog instances onto the stack
.push(cerberus)
.push(rover)
.push(puppy)
End With
Print "Number of dogs on the stack :" ; dogStack.count
Print "Capacity of dog stack :" ; dogStack.capacity
Print "Top dog : "; dogStack.top
dogStack.pop()
Print "Top dog now : "; dogStack.top
Print "Number of dogs on the stack :" ; dogStack.count
dogStack.pop()
Print "Top dog now : "; dogStack.top
Print "Number of dogs on the stack :" ; dogStack.count
Print "Is stack empty now : "; dogStack.empty
Print
Print "Press any key to quit"
Sleep

View file

@ -0,0 +1,6 @@
a = new array
a.push[1]
a.push[2]
a.peek[]
while ! a.isEmpty[]
println[a.pop[]]

View file

@ -0,0 +1,20 @@
[indent=4]
/*
Stack, in Genie, with GLib double ended Queues
valac stack.gs
*/
init
var stack = new Queue of int()
// push
stack.push_tail(2)
stack.push_tail(1)
// pop (and peek at top)
print stack.pop_tail().to_string()
print stack.peek_tail().to_string()
// empty
print "stack size before clear: " + stack.get_length().to_string()
stack.clear()
print "After clear, stack.is_empty(): " + stack.is_empty().to_string()

1
Task/Stack/Go/stack-1.go Normal file
View file

@ -0,0 +1 @@
var intStack []int

1
Task/Stack/Go/stack-2.go Normal file
View file

@ -0,0 +1 @@
intStack = append(intStack, 7)

1
Task/Stack/Go/stack-3.go Normal file
View file

@ -0,0 +1 @@
popped, intStack = intStack[len(intStack)-1], intStack[:len(intStack)-1]

1
Task/Stack/Go/stack-4.go Normal file
View file

@ -0,0 +1 @@
len(intStack) == 0

1
Task/Stack/Go/stack-5.go Normal file
View file

@ -0,0 +1 @@
intStack[len(intStack)-1]

53
Task/Stack/Go/stack-6.go Normal file
View file

@ -0,0 +1,53 @@
package main
import "fmt"
type stack []interface{}
func (k *stack) push(s interface{}) {
*k = append(*k, s)
}
func (k *stack) pop() (s interface{}, ok bool) {
if k.empty() {
return
}
last := len(*k) - 1
s = (*k)[last]
*k = (*k)[:last]
return s, true
}
func (k *stack) peek() (s interface{}, ok bool) {
if k.empty() {
return
}
last := len(*k) - 1
s = (*k)[last]
return s, true
}
func (k *stack) empty() bool {
return len(*k) == 0
}
func main() {
var s stack
fmt.Println("new stack:", s)
fmt.Println("empty?", s.empty())
s.push(3)
fmt.Println("push 3. stack:", s)
fmt.Println("empty?", s.empty())
s.push("four")
fmt.Println(`push "four" stack:`, s)
if top, ok := s.peek(); ok {
fmt.Println("top value:", top)
} else {
fmt.Println("nothing on stack")
}
if popped, ok := s.pop(); ok {
fmt.Println(popped, "popped. stack:", s)
} else {
fmt.Println("nothing to pop")
}
}

View file

@ -0,0 +1,37 @@
def stack = []
assert stack.empty
stack.push(55)
stack.push(21)
stack.push('kittens')
assert stack.last() == 'kittens'
assert stack.size() == 3
assert ! stack.empty
println stack
assert stack.pop() == "kittens"
assert stack.size() == 2
println stack
stack.push(-20)
println stack
stack.push( stack.pop() * stack.pop() )
assert stack.last() == -420
assert stack.size() == 2
println stack
stack.push(stack.pop() / stack.pop())
assert stack.size() == 1
println stack
println stack.pop()
assert stack.size() == 0
assert stack.empty
try { stack.pop() } catch (NoSuchElementException e) { println e.message }

View file

@ -0,0 +1,18 @@
type Stack a = [a]
create :: Stack a
create = []
push :: a -> Stack a -> Stack a
push = (:)
pop :: Stack a -> (a, Stack a)
pop [] = error "Stack empty"
pop (x:xs) = (x,xs)
empty :: Stack a -> Bool
empty = null
peek :: Stack a -> a
peek [] = error "Stack empty"
peek (x:_) = x

View file

@ -0,0 +1,22 @@
import Control.Monad.State
type Stack a b = State [a] b
push :: a -> Stack a ()
push = modify . (:)
pop :: Stack a a
pop = do
nonEmpty
x <- peek
modify tail
return x
empty :: Stack a Bool
empty = gets null
peek :: Stack a a
peek = nonEmpty >> gets head
nonEmpty :: Stack a ()
nonEmpty = empty >>= flip when (fail "Stack empty")

View file

@ -0,0 +1,23 @@
100 LET N=255 ! Size of stack
110 NUMERIC STACK(1 TO N)
120 LET PTR=1
130 DEF PUSH(X)
140 IF PTR>N THEN
150 PRINT "Stack is full.":STOP
160 ELSE
170 LET STACK(PTR)=X:LET PTR=PTR+1
180 END IF
190 END DEF
200 DEF POP
210 IF PTR=1 THEN
220 PRINT "Stack is empty.":STOP
230 ELSE
240 LET PTR=PTR-1:LET POP=STACK(PTR)
250 END IF
260 END DEF
270 DEF EMPTY
280 LET PTR=1
290 END DEF
300 DEF TOP=STACK(PTR-1)
310 CALL PUSH(3):CALL PUSH(5)
320 PRINT POP+POP

View file

@ -0,0 +1,16 @@
procedure main()
stack := [] # new empty stack
push(stack,1) # add item
push(stack,"hello",table(),set(),[],5) # add more items of mixed types in order left to right
y := top(stack) # peek
x := pop(stack) # remove item
write("The stack is ",if isempty(stack) then "empty" else "not empty")
end
procedure isempty(x) #: test if a datum is empty, return the datum or fail (task requirement)
if *x = 0 then return x # in practice just write *x = 0 or *x ~= 0 for is/isn't empty
end
procedure top(x) #: return top element w/o changing stack
return x[1] # in practice, just use x[1]
end

21
Task/Stack/Io/stack.io Normal file
View file

@ -0,0 +1,21 @@
Node := Object clone do(
next := nil
obj := nil
)
Stack := Object clone do(
node := nil
pop := method(
obj := node obj
node = node next
obj
)
push := method(obj,
nn := Node clone
nn obj = obj
nn next = self node
self node = nn
)
)

View file

@ -0,0 +1,6 @@
Stack = Origin mimic do(
initialize = method(@elements = [])
pop = method(@elements pop!)
empty = method(@elements empty?)
push = method(element, @elements push!(element))
)

4
Task/Stack/J/stack-1.j Normal file
View file

@ -0,0 +1,4 @@
stack=: ''
push=: monad def '0$stack=:stack,y'
pop=: monad def 'r[ stack=:}:stack[ r=.{:stack'
empty=: monad def '0=#stack'

6
Task/Stack/J/stack-2.j Normal file
View file

@ -0,0 +1,6 @@
push 9
pop ''
9
empty ''
1

Some files were not shown because too many files have changed in this diff Show more