N/x: Dùng stack
input.txt
651646516546861565468796465468464656498465168464651
8496486541687684651654684651654646541654648654651154615
stack.h
code
typedef struct stack
{
int a;
struct stack *next;
} node;
node*khoitao();
int rong(node*top);
int push(node**top,node**tmp);
int pop(node**top);
stack.c
code
#include"stack.h"
#include<stdio.h>
#include<stdlib.h>
node* khoitao()
{
return(NULL);
}
int rong(node*top)
{
return(top==NULL);
}
int push(node**top,node**tmp)
{
(*tmp)->next=NULL;
if(*top==NULL)
{
*top=*tmp;
}
else
{
(*tmp)->next=*top;
*top=*tmp;
}
return(0);
}
int pop(node **top)
{
int tmp=0;
node*x;
if(rong(*top))
{
printf("Stack rong.\n");
return(0);
}
else
{
tmp=(*top)->a;
x=*top;
*top=(*top)->next;
free(x);
}
return(tmp);
}
cong_so.c
code
#include"stack.h"
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE*in;
node*top1,*top2,*top3,*tmp;
int dk=1,bonus;
char tem;
top1=khoitao();
top2=khoitao();
top3=khoitao();
if((in=fopen("input.txt","r+"))==NULL)
{
printf("Khong mo duoc file");
exit(1);
}
do // Nhap stack 1
{
if((tmp=(node*)malloc(sizeof( struct stack)))==NULL) //tao node
{
printf("khong cap phat duoc bo nho\n");
exit(1);
}
tem=getc(in);
if(tem>='0'&&tem<='9') // lay gia tri
{
tmp->a=tem-48;
push(&top1,&tmp); // them vao stack1
printf("%d",tmp->a);
dk=1;
}
else dk=0;
}while(dk);
free(tmp);
if(rong(top1))
{
printf("Stack1 rong.\n");
return(0);
}
dk=1;
printf("+");
do //nhap stack 2
{
if((tmp=(node*)malloc(sizeof( struct stack)))==NULL) //tao node
{
printf("khong cap phat duoc bo nho\n");
exit(1);
}
tem=getc(in);
if(tem>='0'&&tem<='9') // lay gia tri
{
tmp->a=tem-48;
push(&top2,&tmp); //them vao stack2
printf("%d",tmp->a);
dk=1;
}
else dk=0;
}while(dk);
free(tmp);
if(rong(top2))
{
printf("Stack2 rong.\n");
return(0);
}
/* Cong 2 stack */
printf("=");
bonus=0;
while((rong(top1)&&rong(top2)&&bonus==0)!=1)
{
if((tmp=(node*)malloc(sizeof( struct stack)))==NULL) //tao node
{
printf("khong cap phat duoc bo nho\n");
exit(1);
}
tmp->a= pop(&top1)+pop(&top2)+bonus;
if(tmp->a>=10)
{
tmp->a=tmp->a-10;
bonus=1;
}
else bonus=0;
push(&top3,&tmp);
}
fprintf(in,"\n=\n");
while(top3!=NULL)
{
bonus=pop(&top3);
printf("%d",bonus);
fprintf(in,"%d",bonus);
}
}