2. Add Two Numbers。

来源:互联网 发布:怎么查看手机端口号 编辑:程序博客网 时间:2024/06/08 16:44

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

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


计算两个链表的和,各个节点进行相加,然后有需要进位的则进位到下一个节点上。这个题的思路没有多难,无非就是遍历两个链表,对他们的数值进行相加运算,用一个变量来保存相加之后的总和。使用另一个变量来记录进位的大小。然后每次创建一个新的节点,节点的数值就是总和对于10的余数。需要注意的就是最后面所有相加完成了可能会多出一个节点,因为最后的两个数值可能相加大于10这时候用来保存进行的就需要多加一个节点。还有一点需要注意就是两个节点的长度可能不相同,所以如果节点没有内容了,可以使用0来代替。

#include <iostream>#include <unordered_set>using namespace std;struct ListNode {    int val;    ListNode *next;    ListNode(int x) : val(x), next(NULL) {}};class Solution {public:    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {        ListNode* result = new ListNode(0);//作为新链表的头结点        ListNode* p = result;        int carry = 0;//用来保留两个数相加之后进位的大小        int sum,n1,n2;        while(l1 || l2) {            if(l1) {                n1 = l1->val;            }else {                n1 = 0;            }            if(l2) {                n2 = l2->val;            }else {                n2 = 0;            }            sum = n1 + n2 + carry;            carry = sum / 10;            p->next = new ListNode(sum % 10);            p = p->next;            if(l1)                l1 = l1->next;            if(l2)                l2 = l2->next;        }        if(carry) {            p->next = new ListNode(carry);        }        return result->next;    }};int main() {    Solution s;    ListNode node1(1);    ListNode node2(3);    ListNode node3(9);    ListNode node4(9);    //node1.next = &node2;    node3.next = &node4;    ListNode* p = s.addTwoNumbers(&node1,&node3);    while(p) {        cout << p->val;        cout << endl;        p = p->next;    }}

运行结果可能有误差。

这里写图片描述