面试金典--对链表表示的整数求和
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; }
相关文章推荐
- 给定两个链表表示的整数,编写函数对这两个整数求和,并用链表形式返回结果。
- 《CTCI》2.5 链表表示的整数求和
- 程序员面试金典: 9.2链表 2.5对两个用链表表示的整数求和
- 链式A+B有两个用链表表示的整数,每个结点包含一个数位。这些数位是反向存放的,也就是个位排在链表的首部。编写函数对这两个整数求和,并用链表形式返回结果。 给定两个链表ListNode* A,ListN
- 【Java】对两个用链表表示的整数求和
- leetcode——Add Two Numbers 两个链表表示的正整数对其求和(AC)
- 程序员面试金典(6)两个链表逆向表示的整数求和
- 微软面试之22 一个整数的二进制中表示中的1的个数
- 微软面试100题之20题:输入一个表示整数的字符串,把该字符串转换成整数并输出
- 面试金典--删除未排序链表重复节点
- Leet Code 2 Add Two Numbers - 链表表示的两个数求和 - Java
- 程序员面试题目总结--数组(五)【数组的后面m个数移动为前面m个数、列的前n项数据、判断整数x是否可以表示成n个连续正整数的和、数组中出现奇数次的元素、二维数组中的查找】
- 面试金典--删除链表某个节点,只能访问该节点
- 利用循环链表表示大整数 C语言
- 整数的二进制表示中1的个数 【微软面试100题 第二十八题】
- 面试金典-2.5 链表加法(包含链表的创建)
- 面试金典--以x为基准对链表进行划分
- 算法#25--两整数链表求和
- CCI 2.5 链表整数求和
- 字符型数组表示大整数 并排序、求和(华科保研机试)