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
Analysis: This topic relates to linked list knowledge, about pointers, lists since contact is my weakness, so many years have passed, still has not changed. However, since the crash, or must not hesitate to fight. Analysis of the topic, it is said that there are two linked lists, each of the list of non-negative values, each node of the list is a single digit, the value is stored in reverse order in the list, the sum of the two are returned in the form of a list. After the analysis of the topic information, start it, hey, still scalp tingling ah ~ac code: This topic code to debug, and then to the last AC, can really cost a lot of Kung fu Ah, fortunately, the effort is not negative, hey, the problem code will not upload, the following posted 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) {if (L1 = NULL) ret URN L2; if (L2 = = NULL) return L1; Vector<int> v1; Vector<int> v2; ListNode *head=null, *rear=null; while (L1! = NULL) {v1.push_back (l1->val); L1 = l1->next; } while (L2! = NULL) {v2.push_back (l2->val); L2 = l2->next; }if (V1.size () < V2.size ()) {for (int k=v1.size (); K<v2.size (); k++) v1.push_back (0);} else{for (int k=v2.size (); K<v1.size (); k++) v2.push_back (0);} int temp = 0; int value = 0; for (int j=0; j<v1.size (); j + +) {int sum = V1[j] + v2[j] + temp; temp = Sum/10;value = sum% 10; ListNode *node = new ListNode (value); if (head = = NULL) head = node; if (rear = = NULL) rear = node; else {rear->next = node; Rear = rear->next; }} if (temp! = 0 && rear!=null) {ListNode *node = new ListNode (temp); Rear->next = node; } return head; }};Test main function: In order to facilitate testing, the following provides the main test code, description, in the Leetcode page submission code, only need to upload the solution class:
int main () { ListNode *l1=null, *r1=null, *l2 = NULL, *r2=null, *result=null; int arr1[3] = {2,4,3}; int arr2[3] = {5,6,4}; for (int i=0; i<3; i++) { ListNode *node1 = new ListNode (Arr1[i]); ListNode *node2 = new ListNode (Arr2[i]); if (L1 = = NULL) l1 = Node1; if (r1 = = NULL) r1 = Node1; else{ r1->next = node1; R1 = r1->next; } if (L2 = = NULL) L2 = Node2; if (r2 = = NULL) r2 = Node2; else{ r2->next = node2; r2 = r2->next; } } solution S; result = S.addtwonumbers (L1,L2); for (; result!=null; result=result->next) cout<<result->val<< "--"; Cout<<endl;system ("pause"); return 0;}
Leetcode (2) Add Numbers