问题描述
首先我创建了结构来创建链表。然后创建类和适当的函数来执行某些任务。在时间复杂度的情况下,我可以使用哪些其他方法或算法来使我的解决方案更高效、更快速?
我的解决方案使用了双向链表。我可以使用单个或循环链表来做到这一点吗?
class GiantInt
{
public:
node* head;
node* tail;
int size;
GiantInt()
{
head = tail = NULL;
}
//~GiantInt();
void Insert_at_head(int value)
{
node* temp = new node(value);
if(head == NULL)
{
head = tail = temp;
}
else
{
head->prevIoUs = temp;
temp->next = head;
head = temp;
}
size++;
}
void Insert_at_tail(int value)
{
node* temp = new node(value);
if(tail == NULL)
{
head = tail = temp;
}
else
{
tail->next = temp;
temp->prevIoUs = tail;
tail = temp;
}
size++;
}
void display()
{
node* temp = head;
while(temp != NULL)
{
cout << temp->data;
temp = temp->next;
}
}
int length()
{
return size;
}
void Addition(GiantInt* a,GiantInt* b)
{
int c = 0,s;
GiantInt* a1 = new GiantInt(*a);
GiantInt* b1 = new GiantInt(*b);
this->head = NULL;
this->tail = NULL;
this->size = 0;
while (a1->tail != NULL || b1->tail != NULL)
{
if(a1->tail != NULL && b1->tail != NULL)
{
s = ((a1->tail->data) + (b1->tail->data) + c) % 10;
c = ((a1->tail->data) + (b1->tail->data) + c) / 10;
a1->tail = a1->tail->prevIoUs;
b1->tail = b1->tail->prevIoUs;
}
else if(a1->tail == NULL && b1->tail != NULL)
{
s = ((b1->tail->data) + c) % 10;
c = ((b1->tail->data) + c) / 10;
b1->tail = b1->tail->prevIoUs;
}
else if(a1-> tail != NULL && b1->tail == NULL)
{
s = ((a1->tail->data) + c) % 10;
c = ((a1->tail->data) + c) / 10;
a1->tail = a1->tail->prevIoUs;
}
Insert_at_head(s);
}
if( c != 0)
Insert_at_head(c);
}
};
int main()
{
GiantInt* m = new GiantInt();
GiantInt* n = new GiantInt();
GiantInt* sum = new GiantInt();
string number1,number2;
cout<<" Enter numbers to add: ";
cin >> number1 >> number2;
for(int i = 0; i < number1.length(); i++)
{
m->Insert_at_tail(number1.at(i) - '0');
}
for(int i = 0; i < number2.length(); i++)
{
n->Insert_at_tail(number2.at(i) - '0');
}
cout << "Sum: " << endl;
sum->Addition(m,n);
sum->display();
cout << endl;
return 0;
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)