Viết chương trình chuyển từ hệ 10 sang hệ 8 có sử dụng ngăn xếp

viết chương trình chuyển từ hệ 10 sang hệ 8 có sử dụng ngăn xếp
em xin cảm ơn trước!!!!!
 

VSupport

Ngây thơ trong tối
Tham khảo bài này nhe bạn có thể chuyển về hệ số bất kỳ
Mã:
#include <stdio.h>
#include <stdlib.h>
/*
*/
typedef struct stack
{
    int top;
    int *node;
};
 
 
void Create(stack *s)
{
    s->top = -1;
    s->node = NULL;
}
 
void Push(stack *s,int x)
{
    if(s->top==-1)
    {
        s->node = (int*) malloc (sizeof(int));
        s->top = 0;
        s->node[s->top] = x;
        return;
    }
    s->top++;
    s->node = (int*) realloc (s->node,(s->top+1)*sizeof(int));
    s->node[s->top] = x;
}
 
int Pop(stack *s)
{
    if(s->top != -1)
    {
        int x = s->node[s->top];
        s->top--;
        s->node = (int*) realloc (s->node,(s->top+1)*sizeof(int));
        return x;
    }
}
 
int main()
{
    int number,t;
    printf (" - Enter decimal number: ");scanf("%d",&number);
    printf (" - Convert to: ");scanf("%d",&t);
 
    stack s;
    Create(&s);
    while (number)
    {
        Push(&s,number%t);
        number /=t;
    }
    printf(" - Convert to %d number is: ",t);
    while (s.top!=-1) printf("%d",Pop(&s));
    return 0;
}

Hoặc code khác với hệ số 8:
Mã:
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
 
/* Dinh nghia Stack */
typedef struct node *stack;
 
typedef struct node {
    int data;
    stack pre;
};
// global: s
stack s;
 
// Khoi tao
stack khoitao() {
    s = (stack) malloc(sizeof(struct node));
    if (s == NULL){
        printf("\n ko du bo nho");
        exit(-1); // -1: Error
               }
    else
        s->pre = NULL;
 
    return s;
}
 
// Kiem tra empty
int isempty() {
  return (s->pre == NULL);
}
 
// Them vao stack: Push
void push(int e){
   stack tmp;
   tmp = (stack) malloc(sizeof(struct node));
   if (tmp != NULL){
        tmp->data = e;
        tmp->pre = s->pre;
        s->pre = tmp;
    }
}
 
// Day khoi stack: Pop
void pop(int *t){
    stack tmp;
    if (!isempty()) {
       tmp = s->pre;
       *t = tmp->data; // SAI O DAY
       s->pre = tmp->pre;
       free(tmp);
     }
}
 
// Chuong trinh chinh
int main(void) {
    int r,m;
 
    khoitao();
 
    printf("\n nhap so =");scanf("%d",&m);
 
    // push
    while (m >= 1){
        r = m%8;
        push(r);
        printf("%d",r);
        m /= 8;
    }
    printf("\n");
 
    // pop
    while (!isempty()) {
        pop(&r);
        printf("%d",r);
    }
 
    getch();
}
 

Thống kê

Chủ đề
102,787
Bài viết
470,611
Thành viên
340,593
Thành viên mới nhất
winspire
Top