The title is simple, two lists represent two numbers, and the result of adding two numbers is stored in a new linked list.
The idea is also very simple: two linked list if the same length, the corresponding position added, if a list of more than one, then according to the result of the addition of no carry continue to deal with, after all to consider whether there will be left the rounding.
C + + linked list, the topic has given a very good example:
struct ListNode { int val; *Next; ListNode (int x): Val (x), Next (NULL) {}};
For creating a linked list you can use a head node to point to the list, with no data in the head node
ListNode *l1,*l1head;l1=new ListNode (0); L1head=L1; for (int i=0; i<n;i++) { scanf ("%d",&Temp ); *tempnode=New ListNode (temp); L1->next=Tempnode; L1=l1->next;}
Next directly to the comparison, the situation is considered comprehensive, more dangerous data are
[5],[5]; [1],[99]
1 classSolution {2 Public:3listnode* addtwonumbers (listnode* L1, listnode*L2) {4ListNode *res, *head;5res =NewListNode (0);6Head =Res;7 intFlag =0;8 while(L1! = NULL && L2! =NULL) {9ListNode *tempnode =NewListNode (0);Ten inttemp = l1->val + L2->val +Flag; One if(Temp >=Ten) { AFlag =1; -Tempnode->val = temp%Ten; -}Else { theFlag =0; -Tempnode->val =temp; - } - +L1 = l1->Next; -L2 = l2->Next; +Res->next =Tempnode; Ares = res->Next; at } - while(L1! =NULL) { -ListNode *tempnode =NewListNode (0); - - if(Flag = =1) { - inTempnode->val = L1->val +Flag; - if(Tempnode->val >=Ten) { toFlag =1; +Tempnode->val = tempnode->val%Ten; -}Else { theFlag =0; * } $L1 = l1->Next;Panax NotoginsengRes->next =Tempnode; -res = res->Next; the}Else { +Res->next =L1; A Break; the } + - } $ while(L2! =NULL) { $ListNode *tempnode =NewListNode (0); - - if(Flag = =1) { the -Tempnode->val = L2->val +Flag;Wuyi if(Tempnode->val >=Ten) { theFlag =1; -Tempnode->val = tempnode->val%Ten; Wu}Else { -Flag =0; About } $L2 = l2->Next; -Res->next =Tempnode; -res = res->Next; -}Else { ARes->next =< + Break; the } - $ } the if(Flag = =1) { theListNode *tempnode =NewListNode (1); theRes->next =Tempnode; the } - returnHead->Next; in } the};
ADD Numbers
Ps:
Both the call and the return are using the P->next, because there is no head pointer passing in.
ADD a numbers-c++ linked list operation