Original title: https://leetcode.com/problems/add-two-numbers/
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
Simulates the addition of large integers through a single-linked list. Read the wrong question several times, began to want to complicate, thought is the high number is the chain list head.
The core algorithm is mainly the tail plug Phakian linked list, need to pay attention to two digits of different cases (three while) and how to fill 10 into one (through a flag), the last table header of the empty node also to t off.
My AC code, Complexity O (m+n):
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: Onelistnode* addtwonumbers (listnode* L1, listnode*L2) { AListNode *p=NewListNode (0); -ListNode *l3=NewListNode (0); -ListNode *en=L3; the intflag=0; - while(l1!= NULL && l2!=NULL) { -p=NewListNode (0); -P->val= (L1->val + l2->val +flag)%Ten; + if((L1->val + l2->val+flag) >=Ten) -flag=1; + Else Aflag=0; aten->next=p; -En=en->Next; -L1=l1->Next; -L2=l2->Next; - } - while(l1!=NULL) { inp=NewListNode (0); -P->val= (l1->val+flag)%Ten; to if((L1->val+flag) >=Ten) +flag=1; - Else theflag=0; *en->next=p; $En=en->Next;Panax NotoginsengL1=l1->Next; - } the while(l2!=NULL) { +p=NewListNode (0); AP->val= (l2->val+flag)%Ten; the if((L2->val+flag) >=Ten) +flag=1; - Else $flag=0; $en->next=p; -En=en->Next; -L2=l2->Next; the } - if(flag==1) {//This section can be simplified to en->next=new listnode (1);Wuyip=NewListNode (0); theP->val=1; -en->next=p; WuEn=en->Next; - } AboutL3=l3->Next; $ returnL3; - } -};
Leetcode (2)--ADD-Numbers