欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C语言用栈的思想实现十进制转二进制

程序员文章站 2022-07-15 10:39:23
...
#include <stdio.h>
#include <malloc.h>

typedef int DataType;
typedef struct stacknode
{
    DataType data;
    struct stacknode *next;
} LinkStack;

LinkStack *InitStack()
{
    LinkStack *S;
    S = NULL;
    return S;
}

int EmptyStack(LinkStack *S)
{
    if (S == NULL)
        return 1;
    else
        return 0;
}

LinkStack *Pop(LinkStack *S, DataType *x)
{
    LinkStack *p;
    if (EmptyStack(S))
    {
        printf("\t 栈空,不能出栈!");
        return NULL;
    }
    else
    {
        *x = S->data;
        p = S;
        S = S->next;
        free(p);
        return S;
    }
}

LinkStack *Push(LinkStack *S, DataType x)
{
    LinkStack *p;
    p = (LinkStack *)malloc(sizeof(LinkStack));
    p->data = x;
    p->next = S;
    S = p;
    return S;
}

int GetTop(LinkStack *S, DataType *x)
{
    if (EmptyStack(S))
    {
        printf("\t 栈空!");
        return 0;
    }
    else
    {
        *x = S->data;
        return 1;
    }
}

void ShowStack(LinkStack *S)
{
    LinkStack *p = S;
    if (EmptyStack(S))
    {
        printf("\t 栈空!");
    }
    else
    {
        printf("从栈顶元素起栈中各元素为:");
        while (p != NULL)
        {
            printf("%2d", p->data);
            p = p->next;
        }
    }
}

void D_B(LinkStack *S, DataType x)
{
    while (x)
    {
        S = Push(S, x % 2);
        x /= 2;
    }
    printf("转换后的二进制为:");
    while (!EmptyStack(S))
    {
        S = Pop(S, &x);
        printf("%d", x);
    }
}

int main()
{
    int x;
    LinkStack *Stack;
    Stack = InitStack(Stack);
    // Stack = Push(Stack, 1);
    // Stack = Push(Stack, 2);
    // Stack = Push(Stack, 3);
    // Stack = Pop(Stack, &x);
    // ShowStack(Stack);
    // GetTop(Stack, &x);
    // printf("\n\n%d", x);
    // D_B(Stack, 23);
    return 0;
}