Skip to content

Instantly share code, notes, and snippets.

@Moong-bee
Last active September 23, 2021 17:21
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
C/C++ Stack
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *data;
int capacity;
int top;
} Stack;
void init(Stack *s) {
s -> top = -1;
s -> capacity = 1;
s -> data = (int*)malloc(s -> capacity * sizeof(int));
}
int isEmpty(Stack *s) {
return s -> top == -1;
};
int isFull(Stack *s) {
return s -> top == (s -> capacity - 1);
};
void push(Stack *s, int value) {
if(isFull(s)) {
s -> capacity *= 2;
s -> data = (int*)realloc(s -> data, s -> capacity * sizeof(int));
}
s->data[++(s->top)] = value;
}
int pop(Stack *s) {
if(isEmpty(s)) return printf("Stack is empty..");
else return s->data[(s->top)--];
}
int peek(Stack *s) {
if(isEmpty(s)) return printf("Stack is empty..");
else return s->data[(s->top)];
}
int main() {
Stack s;
init(&s);
push(&s, 1);
push(&s, 2);
push(&s, 3);
push(&s, 4);
push(&s, 5);
printf("Peek: %d\n", peek(&s));
printf("Pop: %d\n", pop(&s));
printf("Peek: %d\n", peek(&s));
printf("Pop: %d\n", pop(&s));
printf("Peek: %d\n", peek(&s));
printf("Pop: %d\n", pop(&s));
printf("Peek %d\n", peek(&s));
return 0;
}
#include <stdio.h>
#define MAX_STACK_SIZE 100
typedef struct {
int arr[MAX_STACK_SIZE];
int top;
} Stack;
void init(Stack *s) {
printf("initialize stack...\n");
s -> top = -1;
printf("initiallize stack complete!\n");
}
int isEmpty(Stack *s) {
return s -> top == -1;
};
int isFull(Stack *s) {
return s -> top == (MAX_STACK_SIZE - 1);
};
void push(Stack *s, int value) {
if(isFull(s)) printf("Stack is full...");
else s->arr[++(s->top)] = value;
};
int pop(Stack *s) {
if(isEmpty(s)) return printf("Stack is empty...");
else return s->arr[(s->top)--];
};
int peek(Stack *s) {
if(isEmpty(s)) return printf("Stack is empty...");
else return s->arr[(s->top)];
};
int main() {
Stack s;
init(&s);
push(&s, 1);
push(&s, 2);
push(&s, 3);
push(&s, 4);
push(&s, 5);
printf("Peek: %d\n", peek(&s));
printf("Pop: %d\n", pop(&s));
printf("Peek: %d\n", peek(&s));
printf("Pop: %d\n", pop(&s));
printf("Peek: %d\n", peek(&s));
printf("Pop: %d\n", pop(&s));
printf("Peek %d\n", peek(&s));
return 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment