Topic:
You are given, linked lists representing, and non-negative numbers. The digits is stored in reverse order and all of their nodes contain a single digit. ADD the numbers and return it as a linked list.
Input: (2, 4, 3) + (5, 6, 4)
Output: 7, 0, 8
Ideas:
First of all, to understand the topic, the input of the two linked list is reversed-order storage. That is, the first digit of the list represents the number of digits, the second represents the number hundred. The next is the same as the general summation, maintaining the current summation results and rounding. Note at the end to determine if there is a carry, if any, you need to generate a bit.
Attention:
1. How to generate a linked list. Maintain a head node. At the same time, continue to link down. Finally, return to the next node of the head junction.
listnode* d = new ListNode (0); listnode* head = D;
D->next = new ListNode (tmp%);d = d->next;
Return head->next;
Complexity: O (N)
AC 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) {//lists in the list of numbers are in reverse storage, the list is the first digit, the second is the hundred, according to The second analogy listnode* c1 = L1; listnode* C2 = L2; listnode* d = new ListNode (0); listnode* head = D; int carry = 0; while (c1! = NULL | | C2! = NULL) {int sum = 0; if (c1! = NULL) {sum + = c1->val; C1 = c1->next; } if (C2! = NULL) {sum + = c2->val; C2 = c2->next; } int tmp = SUM + carry; D->next = new ListNode (tmp% 10); D = d->next; carry = TMP/10; }//If there is a carry, add a bit if (carry! = 0) D->next = new ListNode (carry); Returnhead->next; }};
This problem can also have some expansion content: Add two Numbers--Leetcode
For example, this is actually the addition of BigInteger, the data results do not have to use linked lists, or can be an array, interview may be two kinds of questions and implementation. Then you can test some oo design things, for example, if this is a class should be implemented, that is, the array or linked list as a member variable, and then take these operations as member functions, the further problem may be how to design constructor, This problem is not only basic to the built-in type such as int, long constructor, similar to BigInteger (int num), BigInteger (int long). Overall, the problem is relatively simple, but this problem can not be wrong, so be cautious.
[C + +] leetcode:108 Add Numbers (Reverse-order list summation)