Add Two Numbers题解

来源:互联网 发布:testv淘宝店搜不到 编辑:程序博客网 时间:2024/05/17 18:16

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

题目显得很简单 就是将俩串链表相加 然后有进位的
在算法上 直接的对两个链表进行 扫描 将对应的 数字相加 得到个位与十位 十位作为进位 加到下一位内, 而一旦有一个链表先用完 就作为剩下的数字为0处理。

但是,在链表的实现上比较麻烦,容易出现错误,还有就是判断结束的条件也是有点麻烦,因为如果两个链表都被用完,但是还有进位的话,这个进位也应该被作为下一个节点的值。

所以 解决代码如下:
/** * 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 node(0);        ListNode *solution = &node;int temp,a,b,x,y;b=0;while(l1||l2||b){if(l1){    x=l1->val;l1 = l1->next;    }elsex=0;if(l2){    y=l2->val;l2 = l2->next;     }elsey=0;temp = x + y + b;a = temp%10;b = temp/10;solution -> next = new ListNode(a);            solution = solution -> next;}return node.next;      }};

主要就是在判断结束条件和当一边链表结束后 将其加数作为零的处理  总体来说算是简单的题目。


0 0