[Question]
  [
I can't believe we don't have this already.. It's one of the most important data-structures in programming, yet still simple enough to implement it in a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"):
## Challenge
Your task is to implement a stack that allows pushing and popping numbers, to test your implementation and keep I/O simple we'll use the following setup:
* Input will be a list of non-negative integers
Every positive integer \$n\$ indicates a \$\texttt{push(}n\texttt{)}\$ and every \$0\$ indicates a \$\texttt{pop()}\$ - discarding the top element.
* Output will be the resulting stack
## Example
For example if we're given \$[12,3,0,101,11,1,0,0,14,0,28]\$:
$$
 \begin{aligned}
 & 12 & [12] \\
 & 3 & [3,12] \\
 & 0 & [12] \\
 & 101 & [101,12] \\
 & 11 & [11,101,12] \\
 & 1 & [1,11,101,12] \\
 & 0 & [11,101,12] \\
 & 0 & [101,12] \\
 & 14 & [14,101,12] \\
 & 0 & [101,12] \\
 & 28 & [28,101,12]
 \end{aligned}
$$
Output will be: \$[28,101,12]\$
## Rules
* Input will be a list of non-negative integers in any [default I/O format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
	+ you may use a negative integer to signify the end of a stream of integers
* Output will be a list/matrix/.. of the resulting stack
	+ your choice where the top element will be (at the beginning or end), the output just has to be consistent
	+ output is flexible (eg. integers separated by new-lines would be fine), the only thing that matters is the order
	+ you may use a negative integer to signify the bottom of the stack
* You're guaranteed that there will never be a \$0\$ when the stack is empty
## Examples
```
[] -> []
[1] -> [1]
[1,0,2] -> [2]
[4,0,1,12] -> [12,1]
[8,3,1,2,3] -> [3,2,1,3,8]
[1,3,7,0,0,0] -> []
[13,0,13,10,1,0,1005,5,0,0,0] -> [13]
[12,3,0,101,11,1,0,0,14,0,28] -> [28,101,12]
```
  
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
```
"@?@}x
```
Input is a row vector of numbers.
The final stack is shown upside down, with the most recent element below.
[Try it online!](https://tio.run/##y00syfn/X8nB3qG24v//aEMjHWMdAx1DA0MdQyACMoEcEyBhZBELAA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8F/Jwd6htuJ/bKy6rq56hEvI/@hYrmhDENYx0DEC0iZA2lDHEMS00DEGMo10jMHSxjrmQCkgBPGMQaqAsiC1QGxgYKpjipAFagGLAs0xBCsAckDmGlnEAgA).
### Explanation
```
"         % For each element in the input (implicit)
  @       %   Push current element
  ?       %   If non-zero (this consumes the current element)
    @     %     Push current element again
  }       %   Else
    x     %     Delete most recent element
          %   End (implicit)
          % End (implicit)
          % Display (implicit)
```
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 42 bytes
Since "[the] output is flexible [...], the only thing that matters is the order", this changes the input array into a `0`-terminated array. Example : `[1,0,2]` will return `[2,0,2]` which is to be interpreted as `[2`~~`,0,2`~~`]` = `[2]`.
```
a->{int s=0;for(int v:a)a[v>0?s++:--s]=v;}
```
[Try it online!](https://tio.run/##bVBdb4IwFH33V9z4BKMQ0JkZEM2y52XJ9mh8qAiuCoW0hcwYfju7LfiRuZC095577unhHGhD3cPu2LGiKoWCA/ZerVjuPUWjByyreaJYyfWwqrc5SyDJqZTwThmH8whgQKWiCq@mZDsocGZ9KcH4fr0BKvbSNlSAt5LLukjFgnG13iwhg7ij7vKMLcjYj7JSWLpuQmrTdbP0V9JxQteVm7iJ2i4yImYXhVUqlYR4kAY4t@RSBXcl8cnk1s7JlARkQqb3jCl5QRZ@d@AUezwCPHXl@zMyeyChjhkGJAgMD5tn/eB8ILW9ZfwvsBoqjOewd25fjX@dpEoLr6yVV2FoynoVgp6kp8o@REvzbXBgHMLYjoatzKNJklaqn15QnR7ju/QHg3GDK3fIlSHqR3gtjAcvT/lefSPgODc7KJKBUV2zDcS4gbOrKItgK1J6jKAd@Jdbb2iCIS7Ah1UPhTD8T1JWp4/sk/J9auQJ@KSnX@3/jSLn/4cxLOin21Hb/QI "Java (JDK 10) – Try It Online")
# Previous versions:
## [Java (JDK 10)](http://jdk.java.net/), 60 bytes
```
l->{for(int i;(i=l.indexOf(0))>0;l.remove(i))l.remove(--i);}
```
[Try it online!](https://tio.run/##dVHRToMwFH3fV9z41GppYLi4jI3E@GSi8WGPyx4qK0tnKaQt02Xh27F0iJjFkJZz7jk99xYO7MiCw@6jFUVVagsHx2lthaS3yeSqltcqs6JUnVjV71JkkElmDLwyoeA8AeirxjLrXsdS7KBwGlpbLdR@swWm9wZ7K8BTqUxdcL18EcYun5Xle67TFPJVK4P0nJcaCWVBJEisJBVqx7/echRinIaJpJoX5ZEjgfGAg0DgpGkTn97nbbauq@XGGlj1fQHODflB0QiSkEx/6ZzEJCJTEo8dMXlwLveMirHjbovc3qEwnJHZlcnleDEiUeR9jtx3Dee9qbmM3d16GN0PvriMj4fp/3wukI65qyn@CY9as5NXU@Sxocx0HHUJGCd9wPpkLC9oWVtauf9ikc@4g5sF3AymnLIs49VF/PeoVGO9mXSrab8B "Java (JDK 10) – Try It Online")
**Credits:**
* -1 byte thanks to [O.O.Balance](https://codegolf.stackexchange.com/users/79343/o-o-balance)
## If I can end the program with errors: 55 bytes
(though everything is properly modified)
```
l->{for(int i;;l.remove(--i))l.remove(i=l.indexOf(0));}
```
[Try it online!](https://tio.run/##dVFdb4IwFH33V9z4BFshIDMzoiTLnpZs2YN7Mz5ULFpXCmkvOkP47ax8jLmYpWm5597Duee2R3qiznH3WfM0zxTC0WC3QC7cu3B0k0sKGSPPZFPMi63gMcSCag1vlEsoRwB9ViNF8zllfAepqVkrVFzu1xugaq/tlgrwnEldpEwtXrnGxYtEtmcqiiBZ1sKJyiRTFpcIPAyFq1ianZjlONy2B8SXwuVyx77eE8uz7bCqw1a4l1pvTENkGjUs@5YAZUV@Iv8qJB6Z/MIZCYhPJiS4ZgTk0bDMukoGBpvDN2cTed6UTG9IRqct@sT3W54BD03DWU@qOtvNwIP11vi8s28P7v/cFAiDzGiSneFJKXppq5HVxtqlusFWo2DuphdYXTSy1M0KdHPzJGi1GvcwnsN4IKG6QAmJS@OY5R3FDqGCmGJ8AOvjoLIz3QoGaJxB9Y@0kP2f3YyjZlf1Nw "Java (JDK 10) – Try It Online")
[Answer]
# Sed, 17 Bytes
`:;s/[0-9]\+,0//;t`
-3 bytes thanks to @OMᗺ, -1 thanks to @eggyal
Because you're guaranteed to never pop an empty list, you don't need anything more than an iterated finite state machine. Regular expressions are a tool for building finite state machines, and `sed` can iterate. It's a match made in heaven. 
Takes input from stdin, like so: 
`echo '[12,3,0,101,11,1,0,0,14,0,28]' | sed ':;s/[0-9]\+,0,//;t'`
Outputs the stack in reverse: 
`[12,101,28]`
Could be smaller by two bytes if my local `sed` inherently understood character classes like `\d`, but it doesn't for some reason. 
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~46~~ ~~41~~ 40 bytes
```
$args|%{$x,$a=&({1,$_+$a},{$a})[!$_]};$a
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyWxKL24RrVapUJHJdFWTaPaUEclXlslsVanGkhoRiuqxMfWWqsk/v//39Dov/F/g/@GBob/DYEIyARyTICEkQUA "PowerShell – Try It Online")
Takes input via splatting, e.g., `$z=@(12,3,0,101,11,1,0,0,14,0,28); .\implement-stack.ps1 @z`, which on TIO manifests as separate arguments.
```
$args|%{$x,$a=&({1,$_+$a},{$a})[!$_]};$a    # Full program
$args                                       # Take input via splatting
     |%{                            };      # Loop through each item
              &(              )[!$_]        # Pseudo-ternary, if input is 0 this is 1
        $x,$a=            {$a}              # ... which will pop the first item into $x
           $a=  { ,$_+$a}                   # Else, we append the first item
        $x   =   1                          # ... and drop a dummy value into $x
                                      $a    # Leave $a on pipeline; implicit output
```
*-5 bytes thanks to mazzy.*  
*-1 byte swapping `$_` to `1`*
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~62~~ ~~60~~ ~~56~~ 55 bytes
~~-2~~ -6 bytes thanks to [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)
-1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
Uses the permitted notion of -1 terminated arrays. `f()` calls itself recursively, until fully wound, and then backtracks through the list. `r` keeps track of how many numbers to discard before printing something. Increases if current item is 0, decreases otherwise. If 0, we need not discard, and can print the number.
```
r;f(int*l){~*l?f(l+1),*l?r?r--:printf("%d ",*l):r++:0;}
```
[Try it online!](https://tio.run/##bY7fCoMgFMav11MchIGWglrCSEYPMnYx2hpBizB3Fe3Vm/aXoAv1nN/5vuOXs3eeD4PRBS5rG1ak@4VVVuAqEoS6ymSGsbQxblhgdH4CcpSkJopSrvvBYfg8yhqToAuCk2/tq7W3O1yhE5JCTIFTEFy4y5@x9SQZH3mhwESvN6ucvW42KqYFk3qvjCflBDecrAv2cjXzOVHsUy2BBOeKglrCrV8FpwJ7L9HQfG2LESJ6YfIIxkcwOYLKlf3wBw "C (gcc) – Try It Online")
[Answer]
## Haskell, 28 bytes
```
foldl(#)[]
(_:s)#0=s
s#n=n:s
```
[Try it online!](https://tio.run/##RUztCgIhEPx/TyH4R2ELPzo6DnyEnsAk5Mo68kyy589W/8QyzM7O7Dx8ed5irIEYcq7hFa@RUW7dwC5z4VSYMhSaTJpL3fyaMLX5fCIsv9f0IXsSOLHWgZUNIEAhH5AlyLZOoHFVoLut4YgWTlO6pdBtWYQQI4x/F1/6FXtkD6BovWpyrn6XEP291N2S8w8 "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ṣ0Ṗ;¥/
```
[Try it online!](https://tio.run/##y0rNyan8///hzsUGD3dOsz60VP//4fZHTWvc//@Pjo7V4VKINoSQOgY6RmCWCZBlqGMI4VjoGAM5RjrGUEXGOuZAaSCE8I1BaoEqQDqA2MDAVMcUWR6oESwONM8QrATIAZlvZBEbCwA "Jelly – Try It Online")
### How it works
```
ṣ0Ṗ;¥/  Main link. Argument: A (array)
ṣ0      Split A at zeroes.
    ¥/  Left-reduce the resulting 2D array by this dyadic chain:
  Ṗ       Pop; discard the last element of the left argument.
   ;      Concatenate the result with the right argument.
```
[Answer]
# [R](https://www.r-project.org/), 45 bytes
```
o={};for(e in scan())o="if"(e,c(e,o),o[-1]);o
```
[Try it online!](https://tio.run/##K/r/P9@2utY6Lb9II1UhM0@hODkxT0NTM99WKTNNSSNVJxmI8zV18qN1DWM1rfP/GxpxGXMZcBkaGHIZAhGQCeSYAAkji/8A "R – Try It Online")
* -4 byte thanks to @Giuseppe
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 28 bytes
```
#//.{a___,b_,0,c___}:>{a,c}&
```
[Try it online!](https://tio.run/##TYzNCgIxDITveY3CohDtn4uL4rKP4F2k1OLiHtaD9Fb67HVaLxISvmRmsvr4eq4@LsGX@bIpQsp98s45fjhWHED5NCbPIXdle6brZ3nHm9iN8yTunZwSUcpMSbeBhKlwAGjWjQe2YMP257B8hIhqq61G6NWOVqrn/k9Gqp3xSzcHlvrbDJkoly8 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~59~~ ~~57~~ 51 bytes
```
s=[]
for x in input():s=(s+[x],s[:-1])[x<1]
print s
```
[Try it online!](https://tio.run/##DYdBCoAgEADvvcKj0QatdQjJlyx7jbyouAb2elsYhpnytScnN4YE4unO1XQTk1LeZmcvwcpCnUHIr8gz9Qt5KjWmZmQMQgc7bIAbAiqaOofKnfwD "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 48 bytes
```
s=[]
for x in input():s=([x]+s)[2*0**x:]
print s
```
[Try it online!](https://tio.run/##VY1BCsMgEEX3OcXgKrEu1DQ0CDmJuCqWCMVItNSe3jpKF4Vx@H/m/TF80n54Wd67e1oQymZ7J4SUuGkzPI4TMjhfK7zSOKm4jTqbS5y0pJzSrMwQTucTxIKhGtECHwPOQFZ1bap6gW5lMDcnq@hc9bfGYOFo7gnkehI75wuD5Y@TLduWeF78WJz0X@Vqvg "Python 2 – Try It Online")
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~40~~ 36 bytes
```
([]){{}{({}<>)<>}([]){{}<>}{}([])}<>
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/XyM6VrO6urZao7rWxk7Txq4WKgBkVYPZQNb//4ZGCsYKBgqGBoYKhkAEZAI5JkDCyAIA "Brain-Flak – Try It Online")
Thanks to @Nitrodon for -4 bytes. 
Since Brain-Flak already uses stacks, this is a good puzzle for Brain-Flak.
```
([]){   while items on stack
    {}      pop stack count
    {       if top element is non-zero
        ({}<>)<> push it on the other stack
    }
    if we're here the stack is either empty or there's a 0 on the stack
    ([])    so, count the stack again
    {{}<>{}<>} if there are items left on the stack, pop the stack count and the last item of the other stack
    {} pop the zero or the stack count
    ([]) count the stack again for next round
}
<>  go to the output stack
```
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 89 bytes
```
[N
S S N
_Create_Label_LOOP_1][S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][S N
S _Duplicate_input][N
T   T   S 
_If_neg_Jump_to_Label_EXIT][S N
S _Duplicate_input][N
T   S T N
_If_0_Jump_to_Label_DROP][N
S N
N
_Jump_to_Label_LOOP_1][N
S S S N
_Create_Label_EXIT][S N
N
_Discard_top][N
S S S S N
_Create_Label_LOOP_2][T N
S T _Print_as_integer][S S S T  S T S N
_Push_10_newline][T N
S S _Print_as_character][N
S T S S N
_Jump_to_Label_LOOP_2][N
S S T   N
_Create_Label_DROP][S N
N
_Discard_top][S N
N
_Discard_top][N
S N
N
_Jump_to_Label_LOOP_1]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.  
`[..._some_action]` added as explanation only.
Takes the input-list new-line separated with `-1` to indicate we're done with the inputs.
[Try it online](https://tio.run/##LYrLCYBADETPO1VsA8JGPdiOyILeBAXLjy/RkGS@z37c/TrXrburVpZTLSoxwb8PYgL6K4m4dEHC5DVlZCU6WZPcbdSkJmsmY6GImTcuGuwF).
**Explanation in pseudo-code:**
```
Start LOOP_1:
  Integer i = STDIN as integer
  If(i is negative):
    Call function EXIT
  If(i is 0):
    Call function DROP
  Go to next iteration of LOOP_1
function EXIT:
  Start LOOP_2:
    Pop and print top as integer
    Print newline
    Go to next iteration of LOOP_2
function DROP:
  Drop the top of the stack
  Go to next iteration of LOOP_1
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~60~~ ~~59~~ ~~57~~ 56 bytes
```
l=input()
while 0in l:i=l.index(0);l[i-1:i+1]=[]
print l
```
[Try it online!](https://tio.run/##RYzPCsIwDMbvfYqy06ZR@sdhmfSknn2AspMWFih1SMX59DXZRULIl/y@fPO3TM9s6vl2ufqmaWrymOd3aTvxmTBFqTDLNKBPe8yPuLSqO6WAOz3gVo8@jGJ@YS4yVXoWIi7xLjlr4yqxoLlBgaF5oKlBs3RgSRqwK7ZwJETFm2UXUfZSK9VD/6f0sl4pR68GWjjXuPEH "Python 2 – Try It Online")
---
Saved:
* -1 byte, thanks to pushkin
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~214~~ 150 bytes
```
>>,[>++++++[-<-------->]+<[>+++++[-<++++++++>]]>[-<<<[[-]<],[-]>>>>-<<]>>+[<<+<,----------[++++++++++>-]>[->>-<]>[->+<]>]<<<,]<<[[<]++++++++++<]>>[.>]
```
Reads input as numbers separated by newlines. This must include a single trailing newline. Also expects no leading zeros on each number. Output as a similar newline separated list
[Try it online!](https://tio.run/##RYzBCsNACETv/opryaY95CD@iMwhCRRKoYdAv387G5b0IY4OOtuxvj7P7/5uLaJk6Ema2yCgPmy6OggguLpnGhyFPQgdqqa7erGL1Iuw/tgvT1UKGFPQoxz/wx6Ut0BrdZa7TFKnKpXFkcuDbV7kBw "brainfuck – Try It Online")
# Explanation ~~that isn't really an explanation but is actually just the version I was working on with the comments and stuff which may or may not actually be useful to anyone~~
```
Stack format:
0 (0 \d*)*
>>,[
    Setup digit == '0' conditional
    >++++++
    [-<-------->]
    +
    <[
        Read digit != '0'
        Restore the char code
        cond1 is already 1 at this stage
        >+++++
        [-<++++++++>]
    ]>[
        Read digit == '0'
        -
        Pop previous value
        <<<[
            [-]<
        ]
        Skip next input (assumed to be newline)
        ,[-]
        Skip following loop by unsetting loop flag
        >>>>-
        <<
    ]
    
    Move to next stack frame
    >
    Set loop flag
    >+[
        Set bit used for conditional
        <<+
        Read next character
        <,
        Compare with '\n'
        ----------[
            Not '\n': restore the char code
            ++++++++++
            
            >-
        ]>[
            -
            == '\n': Leave as 0
            Unset loop flag
            >>-
            <
        ]
        
        Copy loop flag along
        >
        [- > + <]
        
        Move to loop flag of next stack frame
        >
    ]
    
    <<<
,]
Fill in with newlines
<<[
    Skip to the cell before this value
    [<]
    Put a newline in there
    ++++++++++
    Move to next value
    <
]
Now the tape has the exact values we need to output
>>[.>]
```
[Answer]
# JavaScript, 40 bytes
Outputs in reverse order.
```
a=>a.map(x=>x?o.push(x):o.pop(),o=[])&&o
```
[Try it online](https://tio.run/##VZBPj8IgEMXP@ik8GUhGLKDZZpN27x7Wg0dsInGpW@MyTVHT/fR1qP8hJPB7bx6T2duzDdumqo8Tjz@uK7POZrkVf7ZmbZa3XyjqU/hlLf@kG9aMA2am4OMxdlv0AQ9OHHDHzNAUMKA1nY4m@cgUQyPfgIwEElA9vUFFcEZQgnzjUkH0p6BJUqBfNU1AkpD2gRo@qJ72qyUqOsZSeQynkyRzmD@c9290dFJ@76AmZG@mR2xKpU@nSq8Gari4z2axWn6LcGwqv6vKf1bSjETjzq4JjnHOxR4rv1n7De8u)
1 byte saved thanks to [Herman L](https://codegolf.stackexchange.com/users/70894/herman-l).
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 32 bytes
```
([]){{}{({}<>)<>}{}<>{}<>([])}<>
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/XyM6VrO6urZao7rWxk7Txq4WRIMwSAJI/f9vaKRgrGCgYGhgqGAIREAmkGMCJIwsFHQNAQ "Brain-Flak – Try It Online")
Uses `-1` to signify the end of the array (but any number will do really).
[Answer]
# [V](https://github.com/DJMcMayhem/V), 10 bytes
```
ò/ 0⏎b2dw0
```
[Try it online!](https://tio.run/##K/v///AmfQUDriSjlHKD//8NDRQMFQyA0FjBVMEAAA "V – Try It Online")
### Explanation
```
ò           " run the following, until an error occurs
 / 0⏎       " | goto next zero with space in front (errors if none)
     b      " | jump one word back (to the beginning of element to pop)
      2     " | twice (element & zero itself)
       dw   " | | delete word
         0  " | goto beginning of line
```
---
## Equivalent in [Vim](https://www.vim.org/), 16 bytes
```
qq/ 0⏎b2dw0@qq@q
```
[Try it online!](https://tio.run/##K/v/v7BQX8GAK8kopdzAobDQofD/f0MDBUMFAyA0VjBVMAAA "V – Try It Online")
### Explanation
Pretty much the same, except recording a macro `q` and recursively call it:
```
qq                " record macro q
  / 0⏎b2dw0       " same as in V
           @q     " recursively call q (aborts on error)
             q    " quit recording
              @q  " execute the macro q
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 21 bytes
```
~c₃Ckt[İ,0]≠∧C⟨hct⟩↰|
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompoe7Omsfbp3wvy75UVOzc3ZJ9JENOgaxjzoXPOpY7vxo/oqM5JJH81cC1db8/x@tEB2roxBtCCZ0DHSMQAwTIMNQxxDMttAxBrKNdIwhKox1zIGSQAjmGoMUAuVByoHYwMBUxxRJGqgLLAw0yxCsAsgBmW1kERsLAA "Brachylog – Try It Online")
-1 byte, and more importantly this feels like a much less clunky way of doing this. 
```
~c₃                     % Partition the input into 3 subarrays
   C                    % Call that array-of-arrays C
    kt[İ,0]             % Its second element should be of the form [Integer, 0]
           ≠            % And its elements shouldn't be equal (i.e. 
                        %   the Integer shouldn't be 0)
            ∧C⟨hct⟩     % Then, remove that [İ, 0] element from C
                   ↰    % And call this predicate recursively
                    |   % When the above fails (when it can't find a partition with 
                        %  [İ, 0] in it), then just output the input
```
Alternate 21 byter: `∋0∧ℕ₁;0;P↺c;Qc?∧P,Q↰|` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompoe7Omsfbp3w/1FHt8GjjuWPWqY@amq0NrAOeNS2K9k6MNkeKBigEwhUXPP/f7RCdKyOQrQhmNAx0DECMUyADEMdQzDbQscYyDbSMYaoMNYxB0oCIZhrDFIIlAcpB2IDA1MdUyRpoC6wMNAsQ7AKIAdktpFFbCwA "Brachylog – Try It Online")
---
Older code:
**22 bytes**
```
∋0&b,1;?z{=|¬∋0&}ˢtᵐ↰|
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FHt4Fako6htX1VtW3NoTVgfu3pRSUPt0541Lah5v//aENjHQMdIGEIJEEsAwNTHVMgAwhj/0cBAA "Brachylog – Try It Online")
```
∋0           If input contains a 0, 
&b           Remove input's first element, getting list of "next" elements
,1           Append 1 to that to handle last element
;?z          Zip that with input
{      }ˢ    Select only zipped pairs where
 =|          both elements are equal (to keep 0s followed by 0s)
   ¬∋0&      or the pair doesn't contain a 0
             this removes both the (pairs containing the) value
              that is followed by a 0, and the 0 itself
tᵐ           Recover back the (filtered) input array elements from the zip
↰            Call this predicate recursively 
|            If input contains no 0s, input is the output 
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
vy>i¨ëy)˜
```
[Try it online](https://tio.run/##MzBNTDJM/f@/rNIu89CKw6srNU/P@f8/2tBIx1jHQMfQwFDHEIiATCDHBEgYWcQCAA) or [verify all test cases](https://tio.run/##MzBNTDJM/W/u5ulir6TwqG2SgpL9/7JKu8xDKw6vrtQ8Ped/ba3O/2jDWK5oQx0DHSMgbaFjrGOoY6RjDBYz1jEHigMhiGcMZAAJQyAJYhkYmOqYImSBWsCihjqGhmAFQI4JyFALoKxBLAA).
**Explanation:**
```
v        # For-each of the items in the input-list:
 y>i     #  If the current item is 0:
  ¨      #   Pop the top item of the list
 ë       #  Else:
  y      #   Push the current item to the stack
   )     #   Wrap the entire stack into a list
         #    i.e. 12 → [12]
         #    i.e. [12] and 3 → [[12], 3]
    ˜    #   Flatten the stack
         #    i.e. [[12], 3] → [12, 3]
         # (and output the list implicitly after the loop)
```
---
**9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) alternative:**
```
vy_i\ëy])
```
[Try it online](https://tio.run/##MzBNTDJM/f@/rDI@M@bw6spYzf//ow2NdIx1DHQMDQx1DIEIyARyTICEkUUsAA) of [verify all test cases](https://tio.run/##MzBNTDJM/W/u5ulir6TwqG2SgpL9/7LK@MyYw6sra2s1/@v8jzaM5Yo21DHQMQLSFjrGOoY6RjrGYDFjHXOgOBCCeMZABpAwBJIgloGBqY4pQhaoBSxqqGNoCFYA5JiADLUAyhrEAgA).
**Explanation:**
```
v        # For-each of the items in the input-list:
 y_i     #  If the current item is 0:
  \      #   Discard top item of the stack
 ë       #  Else:
  y      #   Push the current item to the stack
]        # Close both the if-else and for-each (short for `}}`)
 )       # Wrap the entire stack into a list (and output implicitly)
```
PS: If the output should have been reversed to match the test cases in the challenge description, we can add a trailing `R` to the second version (so **10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**), which reverses the list. [Try it online](https://tio.run/##MzBNTDJM/f@/rDI@M@bw6spYzaD//6MNjXSMdQx0DA0MdQyBCMgEckyAhJFFLAA) or [verify all test cases](https://tio.run/##MzBNTDJM/W/u5ulir6TwqG2SgpL9/7LK@MyYw6sra2s1g/7r/I82jOWKNtQx0DEC0hY6xjqGOkY6xmAxYx1zoDgQgnjGQAaQMASSIJaBgamOKUIWqAUsaqhjaAhWAOSYgAy1AMoaxAIA).
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 18 bytes
```
^
,
+1`,\d+,0
^,
```
[Try it online!](https://tio.run/##NYzBCoAwDEPv@Q4FYTmsm6J/4NEfkDFBD148iP8/M0FKS5OX9j6e89pK2825JBDOMtfd0QOJwJKaLFkKDEbPgF7TaAETo5bAKBA5ylbBYuUiNaX2fuDwM4U/T/f2YYn6L0wv "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
^
,
```
Prefix an extra `,`.
```
+1`,\d+,0
```
Process all pop operations.
```
^,
```
Remove the `,` if it's still there.
Reversing the numbers would cost an extra 8 bytes:
```
O^$`\d+
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 36 bytes
```
->a{b=[];a.map{|x|x>0?b<<x:b.pop};b}
```
[Try it online!](https://tio.run/##VY7RCsIwDEXf9xUDX7PRtA6L2@qHlD604vBFLGPCZO2313SyoZRA78nNTcaXe6ehT5Wyi@u1aW39sH4Jc5gVu7ium8@u9k8fWxeTLrQp4VCpUptC4/bHLIAB3wAncCSAgDtDDtknQRDmIDYuSCBBuYYIONEcvd89IkfRWA6kYqyB5t@FIvsode3TWlytJPIZXO6HyW@bDjT1zV7vS5iCLwc9mZg@ "Ruby – Try It Online")
Anonymous lambda. Outputs in reverse order.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 36 bytes
```
([]){{}{(({}<>))(<>)}{}<>{}<>([])}<>
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/XyM6VrO6urZaQ6O61sZOU1MDSNSCmCAMkgRS//8bGikYKxgoGBoYKhgCEZAJ5JgACSMLAA "Brain-Flak – Try It Online")
```
#Let's call the two stacks in and out
([]){{}                      ([])}    # while not in.empty()
       {        (  )}{}               # if in.peek() != 0
        (({}<>)) <>                   # a = in.pop; out.push(a); out.push(a)
                       <>{}<>         # out.pop()
                                  <>  # switch to out to be printed
```
[Answer]
# Java 10, ~~75~~ 72 bytes
```
n->{var s="";for(int i:n)s=(s+","+i).replaceAll(",\\d+,0","");return s;}
```
Outputs separated by a comma. Top of the stack is last. Try it online [here](https://tio.run/##tVPLbtswELz3KxY8UTAjWHKDGhEcwEBbIEiLHnKMe2BkOqBDUy6XchIY@nZ3SUmuhR6qSymI4mN2ZpcabuVBXm3XL6d9/WR0CaWRiPBdagvHD0BNW6/cRpYKHrwsX7rV0B680/YZ9q4qFSIn4ONPsPXuSTlMighrYt9Ro5eePodKr2FHArwloCDpnjEZMAcljP0CTvbq9niQDnDBWLGpXJACfWMTXHCcMMEmOkmd2hvKcmkMZ2K1Wk/ElHZYUjjla2cBi@bU8xdnJa/Q8ygkwKpXaIs4NgJC6L9gWcCJbAxSTEUe0fkI9EdCZyJrA8JgRMxczAiai1kMOs9G5TYTn0iRnrF1z0KCpBDSpHc6vRbXfxhoawwJZReDqcAs8tAkVJ7PW5I87uVzNjST0wfp1cBNUeHCNAIGZhS9VdXbXpVerZO/XSxLX0tDbosEaW/qoZ3jfdjwniZVvygGeRubXLJG5nf0apdWtSc6SshYvqXbltZem3TpnHzH1Fet/lkIJsBgcQsrxmjYZUVrKwb8x31yea4NKIPqf4t@Xd59@/JZnM/upkP18xY3TKz7Xc3pNw).
Thanks to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%C3%A9goire) for golfing 2 bytes.
Please check out [Kevin Cruijssen's](https://codegolf.stackexchange.com/a/169361/79343) and [Olivier Grégoire's](https://codegolf.stackexchange.com/a/169423/79343) Java answers as well. They take a list-based approach instead, with the latter beating mine by a tidy margin.
Ungolfed:
```
n -> { // lambda taking an integer array as argument and returning a String
    var s = ""; // we'll be using a String to implement and output the stack
    for(int i : n) // loop through the array
        s = (s + "," + i) // append the next number
               .replaceAll(",\\d+,0", ""); // remove any number followed by a zero
    return s; // output the resulting stack
}
```
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), ~~14~~ 12 bytes
```
~{.{;}if}/]`
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPmfp1r9v65ar9q6NjOtVj824X@tap7W/@hYBa5oQzChYKBgBGKYABmGCoZgtoWCMZBtpGAMUWGsYA6UBEIw1xikECgPUg7EBgamCqZI0kBdYGGgWYZgFUAOyGwji1gA "GolfScript – Try It Online")
```
~{.{;}if}/]` Full program, implicit input
~            Eval input
 {      }/   Foreach:
      if       If the value is truthy (!= 0):
  .              Push itself
   {;}         Else: pop the top value
          ]` Push as array representation
             Implicit output
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 17 bytes
*Thanks @sundar and @DomHastings*
```
s/\d+ 0 ?//&&redo
```
[Try it online!](https://tio.run/##K0gtyjH9/79YPyZFW8FAwV5fX02tKDUl//9/QyMFY6CIoYGhgiEQAZlAjgmQMLJQMPiXX1CSmZ9X/F/X11TPwNDgv24BAA "Perl 5 – Try It Online")
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 25 bytes
```
i:?\~~
(0:/:^?
!?l:!<oan;
```
[Try it online!](https://tio.run/##S8sszvj/P9PKPqaujkvDwErfKs6eS9E@x0rRJj8xz/r/fwA "><> – Try It Online") (input must be written in ascii. otherwise use [this one](https://fishlanguage.com/))
### How it works
`i:?\~~` checks for 0, continues to `~~` to delete previous entry. otherwise go down to:
`(0:/:^?` which checks for -1 (no more input), then wrap up to delete -1 and loop:
`!?l:!<oan;` which outputs each number with a newline, then ends when stack emptied
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
Since there's no Husk answer already and it's my favourite golfing-lang:
```
F`?:tø
```
[Try it online!](https://tio.run/##yygtzv6fG5yvnaCtpKBrp6B0Yn3xo6bGokPb/rsl2FuVHN7x////6FiuaEMQ1jHQMQLSJkDaUMcQxLTQMQYyjXSMwdLGOuZAKSAE8YxBqoCyILVAbGBgqmOKkAVqAYsCzTEEKwByQOYaWcQCAA "Husk – Try It Online")
### Explanation
```
F`?:tø  --
F    ø  -- foldl (reduce) with [] as the initial accumulator
 `      -- | flip arguments of
  ?:    -- | | if truthy: apply cons (prepend) to it
    t   -- | | else: return tail
        -- | : returns a function, either prepending the element or dropping 1 element
```
### Alternative solution, 6 bytes
Instead of flipping, we can also just reverse the list and then use a right-fold: [`Ḟ?:tø↔`](https://tio.run/##yygtzv6fG5yvnaCtpKBrp6B0Yn3xo6bGokPb/j/cMc/equTwjkdtU/7//x8dyxVtCMI6BjpGQNoESBvqGIKYFjrGQKaRjjFY2ljHHCgFhCCeMUgVUBakFogNDEx1TBGyQC1gUaA5hmAFQA7IXCOLWAA "Husk – Try It Online")
[Answer]
***Warning:*** Lots of lines ensue. You have been warned.
---
# [CJam](https://sourceforge.net/projects/cjam/), 17 bytes
**Most dangerous code**  
(Assumes the stack elements can be separated by only spaces in the output and that the input array can be whatever form we wish)
```
q~{X0={;}X?}fX]S*
```
[Try it online!](http://cjam.aditsu.net/#code=q%7E%7BX0%3D%7B%3B%7DX%3F%7DfX%5DS*&input=%5B1%200%201%201%5D)
*Explanation*
```
q                                    Reads input string
 ~                                   Instantly convert to array since the string is in the CJam format
  {        }fX                       For loop
   X0=                               If X (the array element currently being checked) is equal to 0
      {;}                            Pop the top element from the stack
         X                           Else push X onto the top of the stack
          ?                          If-Else flag
              ]                      Collate all stack elements into an array
               S*                    Put a space between each array element
```
---
**Alternate Code #1, 27 bytes**  
(Assumes stack elements have to be output in the format shown in the question and that the input array can be whatever form we wish)
```
q~{X0={;}X?}fX]',S+*'[\+']+
```
[Try it online!](http://cjam.aditsu.net/#code=q%7E%7BX0%3D%7B%3B%7DX%3F%7DfX%5D%27%2CS%2B*%27%5B%5C%2B%27%5D%2B&input=%5B1%200%201%201%5D)
*Explanation*
```
q                                    Reads input string
 ~                                   Instantly convert to array since the string is in the CJam format
  {        }fX                       For loop
   X0=                               If X (the array element currently being checked) is equal to 0
      {;}                            Pop the top element from the stack
         X                           Else push X onto the top of the stack
          ?                          If-Else flag
              ]                      Collate stack items into an array
               ',S+                  Add together a comma and a space to create a delimiter
                   *                 Apply the delimiter to the stack
                    '[\+             Append left bracket to the left of the stack text
                        ']+          Append right bracket to the right of the stack text
```
---
**Alternate Code #2, 24 bytes**  
(Assumes the stack elements can be collated in the output and that the input array has to be in the exact format shown in the question)
```
q',/~]S*~{X0={;}X?}fX]S*
```
[Try it online!](http://cjam.aditsu.net/#code=q%27%2C%2F%7E%5DS*%7E%7BX0%3D%7B%3B%7DX%3F%7DfX%5DS*&input=%5B1%2C0%2C1%2C1%5D)
*Explanation*
```
q                        Read input string
 ',/                     Separate by commas (since commas are an invalid array delimiter in CJam)
    ~                    Turn string into an array of substrings that make up the array
     ]S*                 Add spaces in between input numbers to prevent collation in the array
        ~                Turn the string into a valid array representative of the original
         {        }fX    For loop
          X0=            If X (the array element currently being checked) is equal to 0
             {;}         Pop the top element from the stack
                X        Else push X onto the top of the stack
                 ?       If-Else flag
                     ]   Collate all stack elements into an array
                      S* Add a space between each element
```
---
**Safest code for this, 34 bytes**  
(Assumes stack elements have to be output in the format shown in the question and that the input array has to be in the exact format shown in the question)
```
q',/~]S*~{X0={;}X?}fX]',S+*'[\+']+
```
[Try it online!](http://cjam.aditsu.net/#code=q%27%2C%2F%7E%5DS*%7E%7BX0%3D%7B%3B%7DX%3F%7DfX%5D%27%2CS%2B*%27%5B%5C%2B%27%5D%2B&input=%5B1%2C0%2C1%2C1%5D)
*Explanation*
```
q                                      Read input string
 ',/                                   Separate by commas (since commas are an invalid array delimiter in CJam)
    ~                                  Turn string into an array of substrings that make up the array
     ]S*                               Add spaces in between input numbers to prevent collation in the array
        ~                              Turn the string into a valid array representative of the original
         {        }fX                  For loop
          X0=                          If X (the array element currently being checked) is equal to 0
             {;}                       Pop the top element from the stack
                X                      Else push X onto the top of the stack
                 ?                     If-Else flag
                     ]                 Collate stack items into an array
                      ',S+             Add together a comma and a space to create a delimiter
                          *            Apply the delimiter to the stack
                           '[\+        Append left bracket to the left of the stack text
                               ']+     Append right bracket to the right of the stack text
```
---
Thanks to [@Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) for pointing out that the ones with the collated output are invalid since things like `[12]` and `[1,2]` would be indistinguishable.
Thanks also to [@Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) providing a very suitable alternative for the collated outputs and cutting off 9 bytes!
[Answer]
# [Red](http://www.red-lang.org), 64 bytes
```
func[b][a: copy[]foreach n b[either n > 0[insert a n][take a]]a]
```
[Try it online!](https://tio.run/##ZU1BCsMwDLvvFXpC0qys9LBH7Gp8SFuHlkFasuzQ12duDyNjGIMkS3KSqTxkIr6EvoR3HGlg8j3GdduJw5rEjzMiBpIlz5IU3mFoiS9JGR6RKfunwDN7LltaYkaA1n2hrTEMmopflVvYWurgVGrgfmION7Xq1Ko70uo@OnSNadH@u7TqvOofexqVHH@bjssH "Red – Try It Online")
]