Stack realizes data conversion and
sequential storage:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
const int maxn=1e6+10;
typedef struct SNode *stack;
struct SNode{
int data[maxn];
int top;
};
int n;
stack makeStack(){
stack p=(stack)malloc(sizeof(struct SNode));
p->top=-1;
return p;
}
void push(stack p,int x){
if(p->top==maxn-1){
printf("stack is full\n");
return;
}
else{
p->data[++(p->top)]=x;
return;
}
}
int pop(stack p){
if(p->top==-1){
printf("stack is empty\n");
return 0;
}
else{
return p->data[(p->top)--];
}
}
int isEmpty(stack p){
if(p->top==-1)return 1;
else return 0;
}
int main(){
freopen("C:/Users/Administrator/Documents/input.txt","r",stdin);
freopen("C:/Users/Administrator/Documents/output.txt","w",stdout);
while(~scanf("%d",&n)){
if(n==-1)break;
int num=n;
stack p=makeStack();
while(num>0){
int step=num%2;
push(p,step);
num/=2;
}
if(n==0)printf("0--->0\n");
else{
printf("%d--->",n);
while(!isEmpty(p)){
printf("%d",pop(p));
}
printf("\n");
}
}
fclose(stdin);
fclose(stdout);
return 0;
}
Chain storage:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
const int maxn=1e6+10;
typedef struct SNode *stack;
struct SNode{
int data;
stack Next;
};
int n;
stack makeStack(){
stack p=(stack)malloc(sizeof(struct SNode));
p->Next=NULL;
return p;
}
int isEmpty(stack p){
if(p->Next==NULL)return 1;
else return 0;
}
void push(stack p,int x){
stack temp=(stack)malloc(sizeof(struct SNode));
temp->data=x;
temp->Next=p->Next;
p->Next=temp;
}
int pop(stack p){
stack first;
int top;
if(isEmpty(p)){
printf("The stack is empty\n");
return 0;
}
else{
first=p->Next;
p->Next=first->Next;
top=first->data;
free(first);
return top;
}
}
int main(){
freopen("C:/Users/Administrator/Documents/input.txt","r",stdin);
freopen("C:/Users/Administrator/Documents/output.txt","w",stdout);
while(~scanf("%d",&n)){
if(n==-1)break;
int num=n;
stack p=makeStack();
while(num>0){
int step=num%2;
push(p,step);
num/=2;
}
if(n==0)printf("0--->0\n");
else{
printf("%d--->",n);
while(!isEmpty(p)){
printf("%d",pop(p));
}
printf("\n");
}
}
fclose(stdin);
fclose(stdout);
return 0;
}