all tasks

This commit is contained in:
Ingy döt Net 2013-04-11 01:07:29 -07:00
parent b83f433714
commit 68f8f3e56b
14735 changed files with 178959 additions and 0 deletions

14
Task/Stack/0DESCRIPTION Normal file
View file

@ -0,0 +1,14 @@
{{data structure}}[[Category:Classic CS problems and programs]]
A '''stack''' is a container of elements with last in, first out access policy. Sometimes it also called '''LIFO'''. The stack is accessed through its '''top'''. The basic stack operations are:
* ''push'' stores a new element onto the stack top;
* ''pop'' returns the last pushed stack element, while removing it from the stack;
* ''empty'' tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
* ''top'' (sometimes called ''peek'' to keep with the ''p'' theme) returns the topmost element without modifying the stack.
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 reentrant 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.
Create a stack supporting the basic operations: push, pop, empty.

4
Task/Stack/1META.yaml Normal file
View file

@ -0,0 +1,4 @@
---
category:
- Encyclopedia
note: Data Structures

View file

@ -0,0 +1,56 @@
MODE VALUE = STRING; # type of a LINK in this STACK #
MODE LINK = STRUCT(VALUE value, REF LINK next);
MODE STACK = STRUCT(REF LINK first);
STRUCT (
PROC (REF STACK)VOID init,
PROC (REF STACK)BOOL non zero,
PROC (REF STACK, VALUE)VOID append,
PROC (REF STACK)VALUE pop,
PROC (REF STACK)STRING repr,
PROC (REF STACK, STRING)BOOL index error mended
) class stack = (
# PROC init = # (REF STACK self)VOID:
first OF self := NIL,
# PROC non zero = # (REF STACK self)BOOL:
REF LINK(first OF self) ISNT NIL ,
# PROC append = # (REF STACK self, VALUE value)VOID:
first OF self := HEAP LINK := (value, first OF self),
# PROC pop = # (REF STACK self)VALUE: (
IF first OF self IS NIL THEN
STRING message = "pop from empty stack";
IF NOT (index error mended OF class stack)(self, message) THEN
raise index error(message)
FI
FI;
VALUE out = value OF first OF self;
first OF self := next OF first OF self;
out
),
# PROC repr = # (REF STACK self)STRING: (
STRING out := "(",
sep := "";
REF LINK this := first OF self;
WHILE REF LINK(this) ISNT NIL DO
out +:= sep + """" + value OF this + """";
sep := ", ";
this := next OF this
OD;
out+")"
),
# PROC index error mended = # (REF STACK self, STRING message)BOOL:
FALSE # no mend applied #
);
PROC raise index error := (STRING message)VOID: stop;
STACK stack; (init OF class stack)(stack);
[]STRING sample = ("Was", "it", "a", "cat", "I", "saw");
FOR i TO UPB sample DO
(append OF class stack)(stack, sample[i])
OD;
print(((repr OF class stack)(stack), newline))

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,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
}
}

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

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

@ -0,0 +1,21 @@
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 << }
Output:
foo is not empty
foo is empty

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,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 ())))

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;}

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,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))

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.

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,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,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,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)

View file

@ -0,0 +1,84 @@
module stack
public
! Define the data-structure to hold the data
type stack_var
integer, allocatable :: data(:)
integer :: size = 0
end type stack_var
! Set the size of allocated memory blocks
integer, parameter, private :: block_size = 10
contains
! Push ----------------------------------------------------------------------
subroutine push(s, e)
type(stack_var), intent(inout) :: s
integer, intent(in) :: e
integer, allocatable :: wk(:)
if (.not. allocated(s%data)) then
! Allocate space if not yet done
allocate(s%data(block_size))
elseif (s%size == size(s%data)) then
! Grow the allocated space
allocate(wk(size(s%data)+block_size))
wk(1:s%size) = s%data
call move_alloc(wk,s%data)
end if
! Store the data in the stack
s%size = s%size + 1
s%data(s%size) = e
end subroutine push
! Pop -----------------------------------------------------------------------
function pop(s)
integer :: pop
type(stack_var), intent(inout) :: s
if (s%size == 0 .or. .not. allocated(s%data)) then
pop = 0
return
end if
pop = s%data(s%size)
s%size = s%size - 1
end function pop
! Peek ----------------------------------------------------------------------
integer function peek(s)
type(stack_var), intent(inout) :: s
if (s%size == 0 .or. .not. allocated(s%data)) then
peek = 0
return
end if
peek = s%data(s%size)
end function peek
! Empty ---------------------------------------------------------------------
logical function empty(s)
type(stack_var), intent(inout) :: s
empty = (s%size == 0 .or. .not. allocated(s%data))
end function empty
end module stack
program tstack
use stack
implicit none
type(stack_var) :: s
integer :: v
call push(s,1)
call push(s,2)
call push(s,3)
call push(s,4)
do
if (empty(s)) exit
v = pop(s)
write(*,'(a,i0)') 'Popped value off stack = ',v
end do
end program tstack

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,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

View file

@ -0,0 +1,29 @@
public class Stack{
private Node first = null;
public boolean isEmpty(){
return first == null;
}
public Object Pop(){
if(isEmpty())
throw new Exception("Can't Pop from an empty Stack.");
else{
Object temp = first.value;
first = first.next;
return temp;
}
}
public void Push(Object o){
first = new Node(o, first);
}
class Node{
public Node next;
public Object value;
public Node(Object value){
this(value, null);
}
public Node(Object value, Node next){
this.next = next;
this.value = value;
}
}
}

View file

@ -0,0 +1,29 @@
public class Stack<T>{
private Node first = null;
public boolean isEmpty(){
return first == null;
}
public T Pop(){
if(isEmpty())
throw new Exception("Can't Pop from an empty Stack.");
else{
T temp = first.value;
first = first.next;
return temp;
}
}
public void Push(T o){
first = new Node(o, first);
}
class Node{
public Node next;
public T value;
public Node(T value){
this(value, null);
}
public Node(T value, Node next){
this.next = next;
this.value = value;
}
}
}

View file

@ -0,0 +1,5 @@
var stack = [];
stack.push(1)
stack.push(2,3);
print(stack.pop()); // 3
print(stack.length); // 2, stack empty if 0

View file

@ -0,0 +1,8 @@
function Stack() {
this.data = new Array();
this.push = function(element) {this.data.push(element)}
this.pop = function() {return this.data.pop()}
this.empty = function() {return this.data.length == 0}
this.peek = function() {return this.data[0]}
}

View file

@ -0,0 +1,38 @@
global stack$
stack$=""
randomize .51
for i = 1 to 10
if rnd(1)>0.5 then
print "pop => ";pop$()
else
j=j+1
s$ = chr$(j + 64)
print "push ";s$
call push s$
end if
next
print
print "Clean-up"
do
print "pop => ";pop$()
loop while not(empty())
print "Stack is empty"
end
'------------------------------------
sub push s$
stack$=s$+"|"+stack$ 'stack
end sub
function pop$()
if stack$="" then pop$="*EMPTY*": exit function
pop$=word$(stack$,1,"|")
stack$=mid$(stack$,instr(stack$,"|")+1)
end function
function empty()
empty =(stack$="")
end function

View file

@ -0,0 +1,6 @@
make "stack []
push "stack 1
push "stack 2
push "stack 3
print pop "stack ; 3
print empty? :stack ; false

3
Task/Stack/Lua/stack.lua Normal file
View file

@ -0,0 +1,3 @@
stack = {}
table.insert(stack,3)
print(table.remove(stack)) --> 3

View file

@ -0,0 +1,13 @@
mystack = {};
% push
mystack{end+1} = x;
%pop
x = mystack{end}; mystack{end} = [];
%peek,top
x = mystack{end};
% empty
isempty(mystack)

View file

@ -0,0 +1,82 @@
%This class impliments a standard LIFO queue.
classdef LIFOQueue
properties
queue
end
methods
%Class constructor
function theQueue = LIFOQueue(varargin)
if isempty(varargin) %No input arguments
%Initialize the queue state as empty
theQueue.queue = {};
elseif (numel(varargin) > 1) %More than 1 input arg
%Make the queue the list of input args
theQueue.queue = varargin;
elseif iscell(varargin{:}) %If the only input is a cell array
%Make the contents of the cell array the elements in the queue
theQueue.queue = varargin{:};
else %There is one input argument that is not a cell
%Make that one arg the only element in the queue
theQueue.queue = varargin;
end
end
%push() - pushes a new element to the end of the queue
function push(theQueue,varargin)
if isempty(varargin)
theQueue.queue(end+1) = {[]};
elseif (numel(varargin) > 1) %More than 1 input arg
%Make the queue the list of input args
theQueue.queue( end+1:end+numel(varargin) ) = varargin;
elseif iscell(varargin{:}) %If the only input is a cell array
%Make the contents of the cell array the elements in the queue
theQueue.queue( end+1:end+numel(varargin{:}) ) = varargin{:};
else %There is one input argument that is not a cell
%Make that one arg the only element in the queue
theQueue.queue{end+1} = varargin{:};
end
%Makes changes to the queue permanent
assignin('caller',inputname(1),theQueue);
end
%pop() - pops the first element off the queue
function element = pop(theQueue)
if empty(theQueue)
error 'The queue is empty'
else
%Returns the first element in the queue
element = theQueue.queue{end};
%Removes the first element from the queue
theQueue.queue(end) = [];
%Makes changes to the queue permanent
assignin('caller',inputname(1),theQueue);
end
end
%empty() - Returns true if the queue is empty
function trueFalse = empty(theQueue)
trueFalse = isempty(theQueue.queue);
end
end %methods
end

View file

@ -0,0 +1,30 @@
>> myLIFO = LIFOQueue(1,'fish',2,'fish','red fish','blue fish')
myLIFO =
LIFOQueue
>> myLIFO.pop()
ans =
blue fish
>> myLIFO.push('Cat Fish')
>> myLIFO.pop()
ans =
Cat Fish
>> myLIFO.pop()
ans =
red fish
>> empty(myLIFO)
ans =
0

View file

@ -0,0 +1,14 @@
EmptyQ[a_] := If[Length[a] == 0, True, False]
SetAttributes[Push, HoldAll];[a_, elem_] := AppendTo[a, elem]
SetAttributes[Pop, HoldAllComplete];
Pop[a_] := If[EmptyQ[a], False, b = Last[a]; Set[a, Most[a]]; b]
Peek[a_] := If[EmptyQ[a], False, Last[a]]
Example use:
stack = {};Push[stack, 1]; Push[stack, 2]; Push[stack, 3]; Push[stack, 4];
Peek[stack]
->4
Pop[stack]
->4
Peek[stack]
->3

View file

@ -0,0 +1,11 @@
/* lists can be used as stacks; Maxima provides pop and push */
load(basic)$
a: []$
push(25, a)$
push(7, a)$
pop(a);
emptyp(a);
length(a);

View file

@ -0,0 +1,18 @@
exception Stack_empty
class ['a] stack =
object (self)
val mutable lst : 'a list = []
method push x =
lst <- x::lst
method pop =
match lst with
[] -> raise Stack_empty
| x::xs -> lst <- xs;
x
method is_empty =
lst = []
end

View file

@ -0,0 +1,5 @@
stack := IntStack->New();
stack->Push(13);
stack->Push(7);
(stack->Pop() + stack->Pop())->PrintLine();
stack->IsEmpty()->PrintLine();

View file

@ -0,0 +1,8 @@
NSMutableArray *stack = [NSMutableArray array]; // creating
[stack addObject:value]; // pushing
id value = [stack lastObject];
[stack removeLastObject]; // popping
[stack count] == 0 // is empty?

View file

@ -0,0 +1,20 @@
function f()
sys a=1,b=2,c=3,d=4
push a
push b
push c
push d
print a "," b "," c "," d 'result 1,2,3,4
a=10
b=20
c=30
d=40
print a "," b "," c "," d 'result 10,20,30,40
pop a
pop b
pop c
pop d
print a "," b "," c "," d 'result 4,3,2,1
end function
f

31
Task/Stack/Oz/stack.oz Normal file
View file

@ -0,0 +1,31 @@
functor
export
New
Push
Pop
Empty
define
fun {New}
{NewCell nil}
end
proc {Push Stack Element}
NewStack
%% Use atomic swap for thread safety
OldStack = Stack := NewStack
in
NewStack = Element|OldStack
end
proc {Pop Stack ?Result}
NewStack
%% Use atomic swap for thread safety
OldStack = Stack := NewStack
in
Result|NewStack = OldStack
end
fun {Empty Stack}
@Stack == nil
end
end

View file

@ -0,0 +1,18 @@
push(x)=v=concat(v,[x]);;
pop()={
if(#v,
my(x=v[#v]);
v=vecextract(v,1<<(#v-1)-1);
x
,
error("Stack underflow")
)
};
empty()=v==[];
peek()={
if(#v,
v[#v]
,
error("Stack underflow")
)
};

11
Task/Stack/PHP/stack.php Normal file
View file

@ -0,0 +1,11 @@
$stack = array();
empty( $stack ); // true
array_push( $stack, 1 ); // or $stack[] = 1;
array_push( $stack, 2 ); // or $stack[] = 2;
empty( $stack ); // false
echo array_pop( $stack ); // outputs "2"
echo array_pop( $stack ); // outputs "1"

39
Task/Stack/PL-I/stack.pli Normal file
View file

@ -0,0 +1,39 @@
/* Any controlled variable may behave as a stack. */
declare s float controlled;
/* to push a value on the stack. */
allocate s;
s = 10;
/* To pop a value from the stack. */
put (s);
free s;
/* to peek at the top of stack> */
put (s);
/* To see whether the stack is empty */
if allocation(s) = 0 then ...
/* Note: popping a value from the stack, or peeking, */
/* would usually require a check that the stack is not empty. */
/* Note: The above is a simple stack for S. */
/* S can be any kind of data structure, an array, etc. */
/* Example to push ten values onto the stack, and then to */
/* remove them. */
/* Push ten values, obtained from the input, onto the stack: */
declare S float controlled;
do i = 1 to 10;
allocate s;
get list (s);
end;
/* To pop those values from the stack: */
do while (allocation(s) > 0);
put skip list (s);
free s;
end;
/* The values are printed in the reverse order, of course. */

View file

@ -0,0 +1,55 @@
{ tStack is the actual stack type, tStackNode a helper type }
type
pStackNode = ^tStackNode;
tStackNode = record
next: pStackNode;
data: integer;
end;
tStack = record
top: pStackNode;
end;
{ Always call InitStack before using a stack }
procedure InitStack(var stack: tStack);
begin
stack.top := nil
end;
{ This function removes all content from a stack; call before disposing, or before a local stack variable goes out of scope }
procedure ClearStack(var stack: tStack);
var
node: pStackNode;
begin
while stack.top <> nil do
begin
node := stack.top;
stack.top := stack.top^.next;
dispose(node);
end
end;
function StackIsEmpty(stack: tStack):Boolean;
begin
StackIsEmpty := stack.top = nil
end;
procedure PushToStack(var stack: tStack; value: integer);
var
node: pStackNode;
begin
new(node);
node^.next := stack.top;
node^.data := value;
stack.top := node
end;
{ may only be called on a non-empty stack! }
function PopFromStack(var stack: tStack): integer;
var
node: pStackNode;
begin
node := stack.top;
stack.top := node^.next;
PopFromStack := node^.data;
dispose(node);
end;

View file

@ -0,0 +1,5 @@
my @stack; # just a array
@stack.push($elem); # add $elem to the end of @stack
$elem = @stack.pop; # get the last element back
@stack.elems == 0 # true, because the stack is empty
not @stack # also true because @stack is false

1
Task/Stack/Perl/stack.pl Normal file
View file

@ -0,0 +1 @@
sub empty{ not @_ }

View file

@ -0,0 +1,3 @@
(push 'Stack 3)
(push 'Stack 2)
(push 'Stack 1)

View file

@ -0,0 +1,11 @@
% empty? is already defined.
/push {exch cons}.
/pop {uncons exch pop}.
[2 3 4 5 6] 1 push
= [1 2 3 4 5 6]
[1 2 3 4 5 6] pop
=[2 3 4 5 6]
[2 3 4 5 6] empty?
=false
[] empty?
=true

View file

@ -0,0 +1,11 @@
% push( ELEMENT, STACK, NEW )
% True if NEW is [ELEMENT|STACK]
push(ELEMENT,STACK,[ELEMENT|STACK]).
% pop( STACK, TOP, NEW )
% True if TOP and NEW are head and tail, respectively, of STACK
pop([TOP|STACK],TOP,STACK).
% empty( STACK )
% True if STACK is empty
empty([]).

View file

@ -0,0 +1,38 @@
Global NewList MyStack()
Procedure Push_LIFO(n)
FirstElement(MyStack())
InsertElement(MyStack())
MyStack() = n
EndProcedure
Procedure Pop_LIFO()
If FirstElement(MyStack())
Topmost = MyStack()
DeleteElement(MyStack())
EndIf
ProcedureReturn Topmost
EndProcedure
Procedure Empty_LIFO()
Protected Result
If ListSize(MyStack())=0
Result = #True
EndIf
ProcedureReturn Result
EndProcedure
Procedure Peek_LIFO()
If FirstElement(MyStack())
Topmost = MyStack()
EndIf
ProcedureReturn Topmost
EndProcedure
;---- Example of implementation ----
Push_LIFO(3)
Push_LIFO(1)
Push_LIFO(4)
While Not Empty_LIFO()
Debug Pop_LIFO()
Wend

View file

@ -0,0 +1,5 @@
from collections import deque
stack = deque()
stack.append(value) # pushing
value = stack.pop()
not stack # is empty?

View file

@ -0,0 +1,11 @@
from collections import deque
class Stack:
def __init__(self):
self._items = deque()
def append(self, item):
self._items.append(item)
def pop(self):
return self._items.pop()
def __nonzero__(self):
return bool(self._items)

View file

@ -0,0 +1,12 @@
class Stack:
def __init__(self):
self._first = None
def __nonzero__(self):
return self._first is not None
def append(self, value):
self._first = (value, self._first)
def pop(self):
if self._first is None:
raise IndexError, "pop from empty stack"
value, self._first = self._first
return value

View file

@ -0,0 +1 @@
while not stack.empty():

View file

@ -0,0 +1 @@
while stack:

54
Task/Stack/R/stack.r Normal file
View file

@ -0,0 +1,54 @@
library(proto)
stack <- proto(expr = {
l <- list()
empty <- function(.) length(.$l) == 0
push <- function(., x)
{
.$l <- c(list(x), .$l)
print(.$l)
invisible()
}
pop <- function(.)
{
if(.$empty()) stop("can't pop from an empty list")
.$l[[1]] <- NULL
print(.$l)
invisible()
}
})
stack$empty()
# [1] TRUE
stack$push(3)
# [[1]]
# [1] 3
stack$push("abc")
# [[1]]
# [1] "abc"
# [[2]]
# [1] 3
stack$push(matrix(1:6, nrow=2))
# [[1]]
# [,1] [,2] [,3]
# [1,] 1 3 5
# [2,] 2 4 6
# [[2]]
# [1] "abc"
# [[3]]
# [1] 3
stack$empty()
# [1] FALSE
stack$pop()
# [[1]]
[1] "abc"
# [[2]]
# [1] 3
stack$pop()
# [[1]]
# [1] 3
stack$pop()
# list()
stack$pop()
# Error in get("pop", env = stack, inherits = TRUE)(stack, ...) :
# can't pop from an empty list

View file

@ -0,0 +1,36 @@
REBOL [
Title: "Stack"
Author: oofoe
Date: 2010-10-04
URL: http://rosettacode.org/wiki/Stack
]
stack: make object! [
data: copy []
push: func [x][append data x]
pop: func [/local x][x: last data remove back tail data x]
empty: does [empty? data]
peek: does [last data]
]
; Teeny Tiny Test Suite
assert: func [code][print [either do code [" ok"]["FAIL"] mold code]]
print "Simple integers:"
s: make stack [] s/push 1 s/push 2 ; Initialize.
assert [2 = s/peek]
assert [2 = s/pop]
assert [1 = s/pop]
assert [s/empty]
print [lf "Symbolic data on stack:"]
v: make stack [data: [this is a test]] ; Initialize on instance.
assert ['test = v/peek]
assert ['test = v/pop]
assert ['a = v/pop]
assert [not v/empty]

View file

@ -0,0 +1,7 @@
y=123 /*define a REXX variable, value is 123 */
push y /*pushes 123 onto the stack. */
pull g /*pops last value stacked & removes it. */
q=empty() /*invokes the EMPTY subroutine (below)*/
exit /*stick a fork in it, we're done. */
empty: return queued() /*subroutine returns # of stacked items.*/

View file

@ -0,0 +1,5 @@
#lang racket
(define (stack) '())
(define (push x stack) (cons x stack))
(define (pop stack) (values (car stack) (cdr stack)))
(define (empty? stack) (null? stack))

View file

@ -0,0 +1,8 @@
(struct stack ([items #:auto]) #:mutable #:auto-value '())
(define (push! x stack)
(set-stack-items! stack (cons x (stack-items stack))))
(define (pop! stack)
(begin0 (car (stack-items stack))
(set-stack-items! stack (cdr (stack-items stack)))))
(define (empty? stack)
(null? (stack-items stack)))

View file

@ -0,0 +1,3 @@
new stack as s
1 s push
s pop

View file

@ -0,0 +1 @@
s empty if 'stack is empty' print

View file

@ -0,0 +1,15 @@
: stack ( n"- ) create 0 , allot ;
: push ( na- ) dup ++ dup @ + ! ;
: pop ( a-n ) dup @ over -- + @ ;
: top ( a-n ) dup @ + @ ;
: empty? ( a-f ) @ 0 = ;
10 stack st
1 st push
2 st push
3 st push
st empty? putn
st top putn
st pop putn st pop putn st pop putn
st empty? putn

View file

@ -0,0 +1,4 @@
stack = []
stack.push(value) # pushing
value = stack.pop # popping
stack.empty? # is empty?

View file

@ -0,0 +1,80 @@
require 'forwardable'
# A stack contains elements in last-in, first-out order.
# Stack#push adds new elements to the top of the stack;
# Stack#pop removes elements from the top.
class Stack
extend Forwardable
# Creates a Stack containing _objects_.
def self.[](*objects)
new.push(*objects)
end
# Creates an empty Stack.
def initialize
@ary = []
end
# Duplicates a Stack.
def initialize_copy(obj)
super
@ary = @ary.dup
end
# Adds each object to the top of this Stack. Returns self.
def push(*objects)
@ary.push(*objects)
self
end
alias << push
##
# :method: pop
# :call-seq:
# pop -> obj or nil
# pop(n) -> ary
#
# Removes an element from the top of this Stack, and returns it.
# Returns nil if the Stack is empty.
#
# If passing a number _n_, removes the top _n_ elements, and returns
# an Array of them. If this Stack contains fewer than _n_ elements,
# returns them all. If this Stack is empty, returns an empty Array.
nil
if ([].pop(0) rescue false)
# Ruby >= 1.8.7
def_delegator :@ary, :pop
else
# Ruby < 1.8.7
def pop(*args) # :nodoc:
case len = args.length
when 0
@ary.pop
when 1
n = [@ary.length, args.first].min
@ary.slice!(-n, n)
else
raise ArgumentError, "wrong number of arguments (#{len} for 0..1)"
end
end
end
##
# :method: empty?
# Returns true if this Stack contains no elements.
def_delegator :@ary, :empty?
##
# :method: size
# Returns the number of elements in this Stack.
def_delegator :@ary, :size
alias length size
# Converts this Stack to a String.
def to_s
"#{self.class}#{@ary.inspect}"
end
alias inspect to_s
end

View file

@ -0,0 +1,12 @@
s = Stack.new
s.empty? # => true
s.pop # => nil
s.pop(1) # => []
s.push(1) # => Stack[1]
s.push(2, 3) # => Stack[1, 2, 3]
s.pop # => 3
s.pop(1) # => [2]
s.empty? # => false
s = Stack[:a, :b, :c]
s.pop # => :c

View file

@ -0,0 +1,41 @@
dim stack$(10) ' stack of ten
global stack$
global stackEnd
for i = 1 to 5 ' push 5 values to the stack
a$ = push$(chr$(i + 64))
print "Pushed ";chr$(i + 64);" stack has ";stackEnd
next i
print "Pop Value:";pop$();" stack has ";stackEnd ' pop last in
print "Pop Value:";pop$();" stack has ";stackEnd ' pop last in
e$ = mt$() ' MT the stack
print "Empty stack. stack has ";stackEnd
' ------ PUSH the stack
FUNCTION push$(val$)
stackEnd = stackEnd + 1 ' if more than 10 then lose the oldest
if stackEnd > 10 then
for i = 0 to 9
stack$(i) = stack$(i+1)
next i
stackEnd = 10
end if
stack$(stackEnd) = val$
END FUNCTION
' ------ POP the stack -----
FUNCTION pop$()
if stackEnd = 0 then
pop$ = "Stack is MT"
else
pop$ = stack$(stackEnd) ' pop last in
stackEnd = max(stackEnd - 1,0)
end if
END FUNCTION
' ------ MT the stack ------
FUNCTION mt$()
stackEnd = 0
END FUNCTION

View file

@ -0,0 +1,33 @@
class STACK{T} is
private attr stack :LLIST{T};
create:SAME is
res ::= new;
res.stack := #LLIST{T};
return res;
end;
push(elt: T) is
stack.insert_front(elt);
end;
pop: T is
if ~stack.is_empty then
stack.rewind;
r ::= stack.current;
stack.delete;
return r;
else
raise "stack empty!\n";
end;
end;
top: T is
stack.rewind;
return stack.current;
end;
is_empty: BOOL is
return stack.is_empty;
end;
end;

View file

@ -0,0 +1,14 @@
class MAIN is
main is
s ::= #STACK{INT};
#OUT + "push values...\n";
s.push(3);
s.push(2);
s.push(1);
s.push(0);
#OUT + "retrieving them...\n";
loop
#OUT + s.pop + "\n";
until!(s.is_empty); end;
end;
end;

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