实验三 栈的应用——大整数的和
实验目的:
1、了解栈(操作受限的线性表)的操作特性:后进先出LIFO
2、掌握栈顺序/链式存储结构的实现(数据类型定义)
3、熟练掌握栈的基本操作:栈的初始化、出栈、入栈、取栈顶元素等。
实验要求:
熟悉教材算法3.1-3.8,采用链栈的方式完成本次实验任务
实验任务:
1. 编程实现栈的基本操作
2. 使用栈这种数据类型实现“求两个大整数和”的问题
[思路]:
A. 在计算机系统中整数是有最大上限的,所谓大整数就是超过整数最大上限的数,
无法直接用整型来保存;当两个大整数求和时,可以把两个加数看成字符串,将
他们各个位上的数字按序储存在两个栈中,然后将两个栈中弹出对应位上的数字
依次相加
B. 以字符串的方式读入两个大整数,并将其的相应位上的数字从高位到低位分别写
入两个栈中
C. 依次弹出两个的栈顶数字(最低位)相加,并将结果加上进位后的个位数存入
结果栈中,如果相加有进位,则进位置1,否则置0
D. 若其中一个栈为空,则将非空栈的栈顶数字依次弹出与进位相加,和的个位压
入结果栈中,直到栈为空为止
E. 若最高位有进位,则将1压入结果栈中
F. 若两个栈都为空,则结果栈中保存为计算结果,并将其依次输出
[测试数据]
“12344223321122333","432432465657675454”
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct SNode
{
int data;
struct SNode *next;
}LSNode,*LinkStack;
//初始化链栈
void InitStack(LSNode **h)
{
(*h)=(LinkStack)malloc(sizeof(LSNode));
(*h)->next=NULL;
}
//入栈操作
int Push(LinkStack h,int e)
{
LSNode *p;
if((p=(LinkStack)malloc(sizeof(LSNode)))==NULL)
{ printf("内存不足无法建立插入");
return 0;
}
p->data=e;
p->next=h->next;
h->next=p;
return 1;
}
//数组入栈
int MPush(LinkStack h,int *a)
{
int i,j;
int length=0;
//计算数组长度
for(j=0;;j++)
{
if(a[j]=='\0') break;
else length++;
}
for(i=0;i<length;i++)
{
Push(h,a[i]);
}
return 1;
}
//出栈操作
int Pop(LinkStack h,int *e)
{
LSNode *p;
p=h->next;
if(p==NULL)
{
printf("栈空!无法输出!");
return 0;
}
h->next=p->next;
*e=p->data;
free(p);
return 1;
}
//判断栈是否为空
int StackEmpty(LinkStack h)
{
if(h->next==NULL)
return 1;//空返回1
else
return 0;
}
//大整数和
LinkStack function(LinkStack h1,LinkStack h2,LinkStack h3)
{
int e1,e2,e3,sum,r=0;//sum是两数和,r来决定是否进位
while( (StackEmpty(h1)!=1)&&(StackEmpty(h2)!=1) )//两个栈都非空时
{
Pop(h1,&e1);//取h1栈顶元素
Pop(h2,&e2);//取h2栈顶元素
sum=e1+e2+r;//两栈顶元素之和再加上进位
if((sum/10)>1)
{
e3=sum%10;//和大于十,那么取余数把余数放入h3
Push(h3,e3);
r=1;//进位1
}
else
{
e3=sum;//和小于十,把sum赋值给e3,直接把e3放进h3
Push(h3,e3);
r=0;
}
}
while(StackEmpty(h1) != 1)
{//h1非空时
Pop(h1,&e1);
sum=e1+r;
if((sum/10)>1)
{
e3=sum%10;
Push(h3,e3);
r=1;
}
else
{
e3=sum;
Push(h3,e3);
r=0;
}
}
while(StackEmpty(h2) != 1)
{//h2非空时
Pop(h2,&e2);
sum=e2+r;
if((sum/10)>1)
{
e3=sum%10;
Push(h3,e3);
r=1;
}
else
{
e3=sum;
Push(h3,e3);
r=0;
}
}
if(r)//最后的进位
{
Push(h3,r);
}
}
//栈内数据输出
void outStack(LinkStack h)
{
LinkStack t;
t=h;
while(t->next!=NULL)
{
t=t->next;
printf("%d ",t->data);
}
}
int main()
{
int a[100] = { 1,2,3,4,4,2,2,3,3,2,1,1,2,2,3,3,3};
int b[100] = { 4,3,2,4,3,2,4,6,5,6,5,7,6,7,5,4,5,4};
LinkStack h1,h2,h3;
InitStack(&h1);//整数1
InitStack(&h2);//整数2
InitStack(&h3);//结果3
MPush(h1,a);
printf("大整数1:");
outStack(h1);
MPush(h2,b);
printf("\n大整数2:");
outStack(h2);
function(h1,h2,h3);
printf("\n两数相加:\n");
outStack(h3);
}
运行结果