Question
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
Analysis:
This question is not difficult. It mainly involves detail analysis and control. A special case is that after the two columns are traversed, but the carry is 1, a new tail node is created to store this number.
Reference 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) { bool jw=0; int num=0; int sum=0; int count = 0; ListNode *result, *pre_node, *cur_node; while (l1 != NULL && l2 != NULL) { sum = l1->val + l2->val + jw; num = sum % 10; cur_node = (ListNode *)malloc(sizeof(ListNode)); cur_node->val = num; cur_node->next = NULL; if (count == 0) { result = cur_node; pre_node = cur_node; } else { pre_node->next = cur_node; pre_node=pre_node->next; } l1 = l1->next; l2 = l2->next; count++; jw=sum/10; } while (l1 != NULL) { sum = l1->val+jw; num = sum % 10; l1->val=num; cur_node->next = l1; cur_node=cur_node->next; l1 = l1->next; jw=sum/10; } while (l2 != NULL) { sum = l2->val+jw; num = sum % 10; l2->val=num; cur_node->next = l2; cur_node=cur_node->next; l2 = l2->next; jw=sum/10; } if(jw==1) { ListNode *tail=(ListNode *)malloc(sizeof(ListNode)); tail->val=jw; cur_node->next=tail; cur_node=cur_node->next; } cur_node->next = NULL; return result; }};
LeetCode2-Add (two numbers)