2 - Add Two Numbers

来源:互联网 发布:淘宝涉水批文 编辑:程序博客网 时间:2024/05/16 07:44

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

最开始的思路:
将两个链表分别还原为十进制数字,然后相加,再利用该数字生成逆序链表。思路很简单,但是实现起来很复杂。
后来想到,可以模拟加法进位运算。
要注意:代码最后的进位情况。
/** * 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) {                int carry = 0;        ListNode * head = new ListNode(-1);        ListNode * temp = head;        while( l1 != NULL || l2 != NULL ) {                int a = ( l1 == NULL ) ? 0 : l1->val;                int b = ( l2 == NULL ) ? 0 : l2->val;                int c = a + b + carry;                head->next = new ListNode( c % 10);                head =  head->next;                carry = c / 10;                                l1 = (l1 == NULL) ? NULL : l1->next;                l2 = (l2 == NULL) ? NULL : l2->next;        }        if(carry > 0)                head->next = new ListNode(1);        return temp->next;    }};


0 0
原创粉丝点击