Convert (A + B) * C - D ^ E ^ F to postfix and to prefix.
A stack is a LIFO list in which insertion (push) and deletion (pop) happen only at the top. It powers function calls and recursion, undo, bracket matching, and the conversion and evaluation of infix, prefix and postfix expressions — a guaranteed PSC topic.
malloc fails.* / %, then + −. ^ is right-associative, the rest left-associative; postfix and prefix need no parentheses.A stack is an ordered list in which all insertions and deletions are made at one end, called the top. The element inserted last is removed first, so a stack is a LIFO (Last In, First Out) — equivalently FILO (First In, Last Out) — structure. Its behaviour is defined by its operations alone, which makes it an abstract data type (ADT): it can be built on an array or on a linked list without changing how it is used.
| Operation | Effect | Error condition |
|---|---|---|
| push(x) | place x on the top | overflow if the stack is full |
| pop() | remove and return the top element | underflow if the stack is empty |
| peek() / top() | return the top element without removing it | undefined on an empty stack |
| isEmpty() | true when there are no elements | — |
| isFull() | true when no more elements fit (array version) | — |
| size() | number of elements (top + 1 in the array version) | — |
Everyday stacks: plates in a canteen, a pile of books, bangles on a wrist, the Back button of a browser and the Undo command of an editor. Inside every computer, the call stack tracks which functions are running and where each must return.
Array implementation. Keep an array stack[MAX] and an index top that starts at −1 (empty). To push, first increment top and then store (stack[++top] = x); to pop, first read and then decrement (return stack[top--]). The stack is empty when top == -1, full when top == MAX - 1, and holds top + 1 elements.
#include <stdio.h>
#define MAX 5
int stack[MAX];
int top = -1; /* empty stack */
int isEmpty(void) { return top == -1; }
int isFull(void) { return top == MAX - 1; }
void push(int x) {
if (isFull()) { printf("[overflow: %d not pushed] ", x); return; }
stack[++top] = x; /* increment, then store */
}
int pop(void) {
if (isEmpty()) { printf("[underflow] "); return -1; }
return stack[top--]; /* read, then decrement */
}
int peek(void) { return isEmpty() ? -1 : stack[top]; }
int main(void) {
push(10); push(20); push(30);
int x = pop(); /* call separately: argument order */
printf("pop=%d peek=%d\n", x, peek()); /* is unspecified in C -> pop=30 peek=20 */
push(40); push(50); push(60); push(70); /* 70 overflows: MAX = 5 */
printf("\n");
while (!isEmpty()) printf("%d ", pop()); /* 60 50 40 20 10 */
pop(); /* underflow */
printf("\n");
return 0;
}top == -1 and overflow by top == SIZE - 1. Some books start top at 0 and push with stack[top++] = x; then empty is top == 0 and full is top == SIZE. Always read which convention the question uses.Two stacks in one array. Let stack 1 grow upward from index 0 and stack 2 grow downward from index MAX − 1. Neither overflows until the two tops meet (top1 + 1 == top2), so all MAX cells are usable — better than splitting the array into two fixed halves.
Linked implementation. Treat the head of a singly linked list as the top: push inserts a node at the head and pop deletes the head node, both O(1). There is no fixed capacity — overflow happens only when malloc returns NULL — but every element carries an extra pointer.
#include <stdio.h>
#include <stdlib.h>
struct Node { int data; struct Node *next; };
struct Node *top = NULL; /* empty stack */
void push(int x) { /* O(1) */
struct Node *p = malloc(sizeof *p);
if (p == NULL) { printf("Overflow: heap exhausted\n"); return; }
p->data = x;
p->next = top;
top = p;
}
int pop(int *x) { /* O(1); returns 0 on underflow */
if (top == NULL) return 0;
struct Node *p = top;
*x = p->data;
top = p->next;
free(p);
return 1;
}
int main(void) {
int x;
push(1); push(2); push(3);
while (pop(&x)) printf("%d ", x); /* 3 2 1 */
printf("\n");
return 0;
}Function calls and recursion. When a function is called, an activation record (stack frame) holding the return address, parameters, local variables and saved registers is pushed onto the call stack; when the function returns, its frame is popped and control resumes at the saved address. Recursion is simply many frames of the same function. Infinite or very deep recursion exhausts this memory — the famous stack overflow error. Any recursive algorithm can be rewritten iteratively with an explicit stack.
| Step | Event | Call stack (bottom → top) |
|---|---|---|
| 1 | main calls fact(3) | main, fact(3) |
| 2 | fact(3) calls fact(2) | main, fact(3), fact(2) |
| 3 | fact(2) calls fact(1) | main, fact(3), fact(2), fact(1) |
| 4 | fact(1) returns 1 (base case) | main, fact(3), fact(2) |
| 5 | fact(2) returns 2 × 1 = 2 | main, fact(3) |
| 6 | fact(3) returns 3 × 2 = 6 | main |
#include <stdio.h>
int matches(char open, char close) {
return (open == '(' && close == ')') || (open == '[' && close == ']') ||
(open == '{' && close == '}');
}
int isBalanced(const char *s) {
char st[100];
int top = -1;
for (; *s; s++) {
if (*s == '(' || *s == '[' || *s == '{') {
st[++top] = *s; /* push every opener */
} else if (*s == ')' || *s == ']' || *s == '}') {
if (top == -1 || !matches(st[top--], *s))
return 0; /* nothing to match, or wrong type */
}
}
return top == -1; /* leftover openers: unbalanced */
}
int main(void) {
const char *tests[] = {"{[()()]}", "([)]", "((a+b)", "a*(b+c)-{d/[e]}"};
for (int i = 0; i < 4; i++)
printf("%-16s %s\n", tests[i], isBalanced(tests[i]) ? "balanced" : "NOT balanced");
return 0;
}In infix notation the operator sits between its operands (A + B). It is natural for people but needs precedence rules and parentheses to be unambiguous. Prefix notation puts the operator first (+ A B); it is called Polish notation after the logician Jan Łukasiewicz (1924). Postfix notation puts the operator last (A B +) and is called reverse Polish notation (RPN); HP calculators, Forth and PostScript use it directly.
Postfix and prefix need no parentheses and no precedence rules: the order of the symbols alone fixes the order of evaluation, and a single left-to-right scan with a stack evaluates a postfix expression. That is why compilers translate infix expressions into postfix (or into an equivalent expression tree) before generating code.
| Infix | Prefix (Polish) | Postfix (reverse Polish) |
|---|---|---|
A + B | + A B | A B + |
A + B * C | + A * B C | A B C * + |
(A + B) * C | * + A B C | A B + C * |
A * B + C / D | + * A B / C D | A B * C D / + |
(A + B) * (C - D) | * + A B - C D | A B + C D - * |
| Priority | Operators | Associativity | Meaning |
|---|---|---|---|
| Highest | ^ (exponent; written $ in some books) | right to left | A ^ B ^ C = A ^ (B ^ C) |
| Middle | * / % | left to right | A / B * C = (A / B) * C |
| Lowest | + − | left to right | A − B + C = (A − B) + C |
| Special | ( ) | — | ( is pushed and never output; ) pops back to ( |
| Symbol | Action | Stack (bottom → top) | Postfix so far |
|---|---|---|---|
| A | operand → output | empty | A |
| + | stack empty, push + | + | A |
| B | operand → output | + | A B |
* | * outranks +, push | + * | A B |
| C | operand → output | + * | A B C |
| − | pop * (higher), pop + (equal, left-assoc), push − | − | A B C * + |
| ( | push | − ( | A B C * + |
| D | operand → output | − ( | A B C * + D |
| / | top is (, push | − ( / | A B C * + D |
| E | operand → output | − ( / | A B C * + D E |
| ^ | ^ outranks /, push | − ( / ^ | A B C * + D E |
| F | operand → output | − ( / ^ | A B C * + D E F |
| ) | pop ^ and / back to (, discard ( | − | A B C * + D E F ^ / |
* | * outranks −, push | - * | A B C * + D E F ^ / |
| G | operand → output | - * | A B C * + D E F ^ / G |
| end | pop *, then − | empty | A B C * + D E F ^ / G * - |
A + B * C - (D / E ^ F) * G to postfixResult: A B C × + D E F ^ / G × − (written ABC*+DEF^/G*-). Notice that the stack held at most 4 symbols (− ( / ^), that the parentheses never reach the output, and that the operand letters appear in the same order as in the infix expression — only the operators move.
#include <stdio.h>
#include <ctype.h>
int prec(char op) {
switch (op) {
case '^': return 3;
case '*': case '/': case '%': return 2;
case '+': case '-': return 1;
default: return 0; /* '(' */
}
}
void infixToPostfix(const char *in, char *out) {
char st[100];
int top = -1, k = 0;
for (; *in; in++) {
char c = *in;
if (c == ' ') continue;
if (isalnum((unsigned char)c)) {
out[k++] = c; /* operand */
} else if (c == '(') {
st[++top] = c;
} else if (c == ')') {
while (top >= 0 && st[top] != '(') out[k++] = st[top--];
top--; /* discard '(' */
} else { /* operator */
while (top >= 0 && st[top] != '(' &&
(prec(st[top]) > prec(c) || (prec(st[top]) == prec(c) && c != '^')))
out[k++] = st[top--];
st[++top] = c;
}
}
while (top >= 0) out[k++] = st[top--];
out[k] = '\0';
}
int main(void) {
char out[100];
infixToPostfix("A + B * C - (D / E ^ F) * G", out);
printf("%s\n", out); /* ABC*+DEF^/G*- */
infixToPostfix("A ^ B ^ C", out);
printf("%s\n", out); /* ABC^^ */
return 0;
}A ^ B ^ C means A ^ (B ^ C), so its postfix form is A B C ^ ^, not A B ^ C ^. In the algorithm, an incoming ^ does not pop a ^ already on top; every other operator pops an equal-precedence operator.| Symbol | Action | Stack | Output so far |
|---|---|---|---|
| G | output | empty | G |
* | push | * | G |
| ( | push | * ( | G |
| F | output | * ( | G F |
| ^ | push | * ( ^ | G F |
| E | output | * ( ^ | G F E |
| / | ^ is higher: pop it, push / | * ( / | G F E ^ |
| D | output | * ( / | G F E ^ D |
| ) | pop / back to ( | * | G F E ^ D / |
| − | * is higher: pop it, push − | − | G F E ^ D / * |
| C | output | − | G F E ^ D / * C |
* | push (− is lower) | - * | G F E ^ D / * C |
| B | output | - * | G F E ^ D / * C B |
| + | * is higher: pop it; − is equal: keep it; push + | − + | G F E ^ D / * C B * |
| A | output | − + | G F E ^ D / * C B * A |
| end | pop + then − | empty | G F E ^ D / * C B * A + - |
A + B * C - (D / E ^ F) * G: scanning the reversed string G * ( F ^ E / D ) - C * B + AReversing the output gives the prefix form − + A × B C × / D ^ E F G (written -+A*BC*/D^EFG). Check it with the expression tree: the root is the last operator applied, −; its left operand is A + (B × C) → + A * B C, and its right operand is (D / E^F) × G → * / D ^ E F G.
(left op right) for infix, op left right for prefix. Example: A B + C D + * → * + A B + C D.left right op. Example: * + A B - C D → A B + C D - *.A B C * + but the prefix is + A * B C, not + * C B A.| Token | Action | Stack (bottom → top) |
|---|---|---|
| 6, 2, 3 | push three operands | 6 2 3 |
| + | 2 + 3 = 5 | 6 5 |
| − | 6 − 5 = 1 | 1 |
| 3, 8, 2 | push three operands | 1 3 8 2 |
| / | 8 / 2 = 4 | 1 3 4 |
| + | 3 + 4 = 7 | 1 7 |
* | 1 × 7 = 7 | 7 |
| 2 | push | 7 2 |
| ^ | 7 ^ 2 = 49 | 49 |
| 3 | push | 49 3 |
| + | 49 + 3 = 52 | 52 → result |
6 2 3 + - 3 8 2 / + * 2 ^ 3 +#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int ipow(int b, int e) { int r = 1; while (e-- > 0) r *= b; return r; }
int evalPostfix(const char *expr) {
int st[100], top = -1;
char buf[200];
strcpy(buf, expr);
for (char *tok = strtok(buf, " "); tok != NULL; tok = strtok(NULL, " ")) {
if (isdigit((unsigned char)tok[0])) {
st[++top] = atoi(tok); /* operand: push */
} else {
int b = st[top--]; /* first pop = RIGHT operand */
int a = st[top--]; /* second pop = LEFT operand */
switch (tok[0]) {
case '+': st[++top] = a + b; break;
case '-': st[++top] = a - b; break;
case '*': st[++top] = a * b; break;
case '/': st[++top] = a / b; break;
case '^': st[++top] = ipow(a, b); break;
}
}
}
return st[top];
}
int main(void) {
printf("%d\n", evalPostfix("6 2 3 + - 3 8 2 / + * 2 ^ 3 +")); /* 52 */
printf("%d\n", evalPostfix("5 3 4 * 6 / +")); /* 7 */
return 0;
}Prefix evaluation is the mirror image: scan from right to left, push operands, and on an operator pop A (now the left operand) and then B, and push A op B. For - + 8 / 6 3 2: push 2, 3, 6; ‘/’ pops 6 and 3 → 2; push 8; ‘+’ pops 8 and 2 → 10; ‘−’ pops 10 and 2 → 8. The value is 8, matching (8 + 6/3) − 2.
8 2 / into 2 / 8 and 6 5 - into −1 instead of 1. Addition and multiplication hide this mistake; subtraction, division and ^ expose it.Suppose the numbers 1, 2, …, n arrive in this order and each must be pushed, but pops may be done at any moment. Which output orders are possible? Not all n! of them: once a larger number is popped, every smaller number still inside the stack must come out in decreasing order. The number of achievable outputs is the Catalan number.
| Output | Push/pop sequence | Possible? |
|---|---|---|
| 1 2 3 | S X S X S X | yes |
| 1 3 2 | S X S S X X | yes |
| 2 1 3 | S S X X S X | yes |
| 2 3 1 | S S X S X X | yes |
| 3 2 1 | S S S X X X | yes |
| 3 1 2 | after 3 is popped, 2 sits above 1 | no |
Testing a sequence: simulate it. For each output number, push input numbers until that number is on top, then pop it; if the needed number is already in the stack but buried below the top, the sequence is impossible. Equivalently, an output is impossible exactly when it contains a ‘3-1-2’ pattern: some number x followed later by a smaller number a and then by a number b with a < b < x.
Try the problem first, then reveal the working one step at a time.
Convert (A + B) * C - D ^ E ^ F to postfix and to prefix.
Evaluate 8 2 3 ^ / 2 3 * + 5 1 * -.
The numbers 1, 2, 3, 4, 5 are pushed in this order, with pops allowed at any time. Can the output be (a) 3 2 5 4 1? (b) 4 2 3 1 5?
Check {[()]()} and {[(])} with a stack.
Convert the infix expression (a + b * c) + ((d * e + f) * g) to postfix.
Give the prefix form of P + Q * M - N.
Evaluate the prefix expression + * 2 3 - 9 / 8 4.
Two stacks share one array A[0..9]: stack 1 starts with top1 = −1 and grows upward; stack 2 starts with top2 = 10 and grows downward. Give the push operations for each stack and the overflow condition.
If 1, 2, 3, 4, 5 are pushed in order with pops allowed at any time, how many different output sequences are possible? Is 5 3 4 1 2 one of them?
A B C * + gives + * C B A, but the prefix of A + B × C is + A * B C.12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.
AB+CD+* into prefix form.