栈用于2进制转换10进制

#include <stdio.h>
#include <stdlib.h>
#include<math.h>
struct Node;
typedef struct Node* ptrToNode;
typedef ptrToNode Stack;
int len = 0;
struct Node{
    char bin;
    Stack Next;
};

Stack
createStack(){
    Stack s = malloc(sizeof( struct Node ));
    if(s == NULL){
        return 0;
    }
    s->Next = NULL;
    return s;
}

int
IsEmpty(Stack s){
    return (s->Next == NULL);
}
char
pop(Stack s){
    ptrToNode firstCell;
    if(s == NULL)
        return 0;
    else{
        char c;
        firstCell = s->Next;

        c = firstCell->bin;
        s->Next = firstCell->Next;
        free(firstCell);
        len--;
        return c;
    }

}

void
push(Stack s,char c){
    ptrToNode cell = malloc(sizeof(struct Node ));
    cell->bin = c;
    cell->Next = s->Next;
    s->Next = cell;
    len++;
}

int main()
{
    int sum = 0,tmp;
    char ch;
    Stack s;
    int i,tim;
    s = createStack();
    scanf("%c",&ch);
    while(ch != '#'){
        push(s,ch);
        scanf("%c",&ch);
    }
    tim = len;
    for(i = 0; i < tim; i++){
        ch = pop(s);
        tmp = ch - 48;
        sum += (tmp * pow(2,i));
    }
    printf("%d",sum);
    return 0;
}
View Code

之前用getchar()容易出问题,改用scanf()

改天看看缓冲区的问题

原文地址:https://www.cnblogs.com/gabygoole/p/4971728.html