Problem:
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:
Two single-linked list of numbers added, and then the results are represented by a single linked list, to investigate the basic operation of the list, pay attention to the rounding
Attention:
Class Solution {public: listnode *addtwonumbers (ListNode *l1, ListNode *l2) {
The two linked list pointers given by the topic L1, L2 Common sense point to the first valid element, not a pointer to a head node. Therefore, the returned pointer is also a pointer to a valid node, not to the head node.
Also: Linked list is best to use the presentation method of the lead node, convenient list operation!! The data field of the head node is useless, arbitrarily initialized, with its pointer field.
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) {int flag = 0; listnode* tail = new ListNode (0); listnode* ptr = tail; while (L1! = NULL | | L2! = NULL) {int val1 = 0; if (L1! = NULL) {val1 = l1->val; L1 = l1->next; } int val2 = 0; if (L2! = NULL) {val2 = l2->val; L2 = l2->next; } int tmp = VAL1 + val2 + flag; Ptr->next = new ListNode (tmp% 10); flag = TMP/10; PTR = ptr->next; } if (flag = = 1) {Ptr->next = new ListNode (1); } return tail->next; }};
Leetcode | | Add Numbers problem