Skip to content

Instantly share code, notes, and snippets.

@sortira
Created November 20, 2025 05:29
Show Gist options
  • Select an option

  • Save sortira/55b2f343562651175079c6bc94309e0d to your computer and use it in GitHub Desktop.

Select an option

Save sortira/55b2f343562651175079c6bc94309e0d to your computer and use it in GitHub Desktop.
generate stack perm
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
void generate(int input[], int n, int in,
int stack[], int top,
int output[], int out) {
//if input and stack empty we reached base case
if (in == n && top == -1) {
for (int i = 0; i < out; i++) {
printf("%d ", output[i]);
}
printf("\n");
return;
}
// either we can push from input to stack
if (in < n) {
stack[++top] = input[in];
generate(input, n, in + 1, stack, top, output, out);
top--; // backtrack
}
//or we can pop from stack to output
if (top != -1) {
int val = stack[top--];
output[out++] = val;
generate(input, n, in, stack, top, output, out);
out--; // backtrack
stack[++top] = val; // restore
}
}
int main() {
int n;
printf("Enter n: ");
scanf("%d", &n);
int input[MAX];
printf("Enter %d elements of the input:\n", n);
for(int i = 0; i < n; i++) scanf("%d", &input[i]);
int stack[MAX], output[MAX];
printf("All possible stack permutations:\n");
generate(input, n, 0, stack, -1, output, 0);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment