欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

基于动态链表的“大整数加法运算器”

程序员文章站 2024-03-23 15:54:28
...

代码写得比较菜>_<

#include<iostream> //基于动态链表的“大整数加法运算器”
#include<cstring>
#define N 100
using namespace std;
struct node
{
	int x;
	node *next;
};
node *head_a = NULL;  
node *tail_a = NULL;
node *head_b = NULL; 
node *tail_b = NULL;
int len_a=0, len_b=0, index=0;  //index是记录答案长度最大下标
char *a = new char[N];
char *b = new char[N];
int *s = new int[N];  //储存答案

node *createnode(int i,char *s) 
{
	node *temp = new node;
	temp->x = s[i] - '0';
	temp->next = NULL;
	return temp;
}
void createlist(int i, node** head, node** tail, char *s) 
{
	while(i >= 0)
	{
		node *temp = createnode(i,s);
		if(*head == NULL)  
		{
			*head = temp;
		}
		else
		{
			(*tail)->next = temp;  
		}
		*tail = temp;
		i--;
	}
}
void add() //主要实现
{
	int n=0;
	node *p1=head_a, *p2=head_b;
	while(p1->next!=0 && p2->next!=0) //只算到最大相等位数那一位
	{
		s[n] = p1->x + p2->x;
		n++;
		p1 = p1->next;
		p2 = p2->next;
	}
	s[n] = p1->x + p2->x;  //这里指向相等的那一位数
	if(p1->next!=0 && p2->next==0)  //如果p1还有下一位
	{
		n++;
		p1 = p1->next;
		index = len_a-1;  //可以确定答案的长度了
		while(1)  //把剩下的都赋值给s
		{
			s[n] = p1->x;
			if(p1->next==0) break;   //如果是最后一位停止
			n++;
			p1 = p1->next;
		}
	}
	if(p1->next==0 && p2->next!=0)  //如果p2还有下一位
	{
		n++;
		p2=p2->next;
		index=len_b-1;
		while(1)  //把剩下的都赋值给s
		{
			s[n] = p2->x;
			if(p2->next==0) break;
			n++;
			p2 = p2->next;
		}
	}
	int k=0;
	while(1)
	{
		if(index==0)  break;
		if(s[k] >= 10)  //除了最后一个大于9的数不用管,把其他大于9的进位
		{
			s[k] -= 10;
			s[k+1]++;
		}
		k++;
		if(k == index) break;
	}
}
void deletelist(node *p)
{
	node *w=p,*v=NULL;
	while(w)
	{
		v = w;
		w = w->next;
		delete v;
	}
}
int main()
{
	cin >> a >> b; 
	len_a = strlen(a);
	len_b = strlen(b);
	node** head1 = &head_a;
	node** tail1 = &tail_a; 
	node** head2 = &head_b; 
	node** tail2 = &tail_b; 
	createlist(len_a-1,head1,tail1,a);
	createlist(len_b-1,head2,tail2,b);
	index = len_a-1;  //(最大下标肯定是大数的位数,先默认为 a的长度)
	add();
	cout << a << " + " << b << " = ";
	for(int i=index; i>=0; i--)
		cout << s[i];
	deletelist(head_a);
	deletelist(head_b);
	delete []a;
	delete []b;
	delete []s;
	return 0;
}