0% found this document useful (0 votes)
8 views

Stack

Uploaded by

phong160705
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Stack

Uploaded by

phong160705
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <stdlib.h>

// Định nghĩa cấu trúc ngăn xếp động


typedef struct {
int *items;
int top;
int capacity;
} Stack;

void initStack(Stack *s) {


s->capacity = 1;
s->top = -1;
s->items = (int *)malloc(s->capacity * sizeof(int));
}

int isEmpty(Stack *s) {


return s->top == -1;
}

void resizeStack(Stack *s) {


s->capacity *= 2;
s->items = (int *)realloc(s->items, s->capacity * sizeof(int));
}

void push(Stack *s, int value) {


if (s->top == s->capacity - 1) {
resizeStack(s);
}
s->items[++(s->top)] = value;
}

int pop(Stack *s) {


if (!isEmpty(s)) {
return s->items[(s->top)--];
} else {
printf("Stack underflow\n");
return -1;
}
}

void convertToBase(int n, int base) {


Stack stack;
initStack(&stack);
char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

if (base < 2 || base > 36) {


printf("Base must be between 2 and 36\n");
return;
}

while (n > 0) {
push(&stack, n % base);
n /= base;
}

printf("Converted number: ");


while (!isEmpty(&stack)) {
printf("%c", digits[pop(&stack)]);
}
printf("\n");

free(stack.items);
}

int main() {
int n, base;

printf("Enter the number to be converted: ");


scanf("%d", &n);

printf("Enter the base to convert to: ");


scanf("%d", &base);

convertToBase(n, base);

return 0;
}

You might also like