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

#include 
#include 

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;
}

你可能感兴趣的:(栈,数据结构,算法,c语言)