← The C Language Lesson 72 of 77 · 10 XP

The stack

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A stack is a "pile of plates": we put things on top (push) and take them from the top (pop). Last in, first out (LIFO).

The simplest way is to build a stack on an array:

#define CAP 100
char stack[CAP];
int top = 0;                     // how many items are in the stack

void push(char c)  { stack[top++] = c; }
char pop(void)     { return stack[--top]; }
int  empty(void)   { return top == 0; }

In real code you need to check for overflow (top == CAP) and for an attempt to take from an empty stack.

Where you meet a stack: the function call stack (the very one that overflows with endless recursion), undoing actions (Ctrl+Z), depth-first traversal, evaluating expressions, checking brackets in code editors and compilers.

Task. Check whether the brackets ()[]{} are placed correctly in a string without spaces. Every opening bracket goes onto the stack. On a closing bracket, the top of the stack must be its matching opening bracket. At the end the stack must be empty. Print yes or no.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.