@zimenglan
2015-01-20T12:25:54.000000Z
字数 1150
阅读 1183
leetcode merge
题目大意:
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
题目翻译:
给定两个链表表示两个非负数。数字逆序存储,每个节点包含一个单一的数字。计算两个数的和,并以链表的形式返还。
分析:
要考虑进位。表示结果的结点要new出来。
Code
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/class Solution {public:ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {ListNode* anno = NULL;if(l1 == anno) return l2;if(l2 == anno) return l1;ListNode *res = NULL;ListNode *p = NULL;int las = 0;int v;const int base = 10;while(l1 != anno && l2 != anno) {las += l1->val;las += l2->val;v = las % base;if(res == NULL) {res = new ListNode(v);p = res;} else {p->next = new ListNode(v);p = p->next;}// refreshl1 = l1->next;l2 = l2->next;las = las / base;}while(l1 != anno) {las += l1->val;v = las % base;p->next = new ListNode(v);p = p->next;// refreshlas = las / base;l1 = l1->next;}while(l2 != anno) {las += l2->val;int v = las % base;p->next = new ListNode(v);p = p->next;// refreshlas = las / base;l2 = l2->next;}// don't forget the last oneif(las >= 1) {p->next = new ListNode(las);p = p->next;}return res;}};