您的位置:首页 > 职场人生

面试金典--对链表表示的整数求和

2014-06-15 13:08 281 查看
题目描述:给定两个链表,逆序表示两个整数,对这两个链表进行求和。

思路:注意进位即可,可以就地操作,但是实现稍微麻烦一点(如果不就地的话,可以转化成递归操作,代码更加简洁)

#include <iostream>
#include <string>
#include <fstream>
#include <map>
#include <algorithm>
#include <vector>
#include <ctime>
#include <bitset>

using namespace std;

template<typename T>
class Node
{
public:
Node<T> *next;
T data;

Node(T d):data(d),next(NULL){}
void appendToTail(T d)
{
Node<T> *end = new Node<T>(d);
Node<T> *n = this;
while(n->next != NULL)
{
n = n->next;
}
n->next = end;
}
};

int main()
{
Node<int> *head1 = new Node<int>(7);
head1->appendToTail(1);
head1->appendToTail(6);
Node<int> *head2 = new Node<int>(5);
head2->appendToTail(9);
head2->appendToTail(2);
//2.4
int c = 0;
Node<int> *resHead = NULL;
if(head1 == NULL)
{
resHead = head1;
}
else if(head2 == NULL)
{
resHead = head2;
}
else
{
resHead = head1;
Node<int> *restmp = head1;
while(head1 != NULL && head2 != NULL)
{
int tmp1 = head1->data;
int tmp2 = head2->data;
restmp->data = (tmp1+tmp2+c)%10;
c = (tmp1+tmp2)/10;
head1 = head1->next;
head2 = head2->next;
if(head1 != NULL)
{
restmp = restmp->next;
}
else
{
restmp->next = head2;
if(head2 != NULL)
restmp = restmp->next;
}
}
while(head1 != NULL)
{
int tmp1 = head1->data;
restmp->data = (tmp1+c)%10;
c = (head1->data+c)/10;
head1 = head1->next;
if(restmp->next != NULL)
restmp = restmp->next;
}
while(head2 != NULL)
{
int tmp2 = head2->data;
restmp->data = (tmp2+c)%10;
c = (tmp2+c)/10;
head2 = head2->next;
if(restmp->next != NULL)
restmp = restmp->next;
}
if(c != 0)
restmp->next = new Node<int>(c);
}
while(resHead != NULL)
{
cout<<resHead->data<<endl;
resHead = resHead->next;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐