Problem:
Two linked lists simulate the addition of large integers.
Answer:
1) Use recursive implementations.
is better than using iterative implementations directly.
The addition needs to start at the lowest bit, and when the recursive implementation is used, it is recursive to the bottom (len==1), then back to the previous level, followed by the return carry number. This saves the time to locate the same layer node every time, compared to the direct iteration implementation.
1 intLengthConstnode*head)2 {3 intLength =0;4 while(Head! =NULL)5 {6length++;7Head = head->Next;8 }9 Ten returnlength; One } A - //Heada refers to the length of the linked list is not less than headb - int__add (node* Heada,intLenA, node* headb,intLenB) the { - intsum =-1; - if(LenA = =1) -sum = Heada->data + headb->data; + Else if(LenA >LenB) -sum = Heada->data + __add (heada->next,--LenA, HEADB, LenB); + Else//now, only Lena = = Lena is left. Asum = heada->data + Headb->data + __add (heada->next,--lena, Headb->next,--LenB); at -Heada->data = sum%Ten; - returnSum/Ten; - } - -node* Add (node* lista,node*Listb) in { - if(ListA = =NULL) to returnListb; + if(Listb = =NULL) - returnListA; the * intLenA =length (ListA); $ intLenB =length (LISTB);Panax Notoginsengnode* longer =ListA; -node* shorter =Listb; the if(LenA <LenB) + { Alonger =Listb; theShorter =ListA; + } - $ intcarry =__add (longer, LenA, shorter, LenB); $ if(Carry! =0) - { -node* head =NewNode (carry); theHead->next =longer; -longer =head;Wuyi } the - returnlonger; Wu}
2) Iterative implementation
The direct iterative implementation is a waste of time, when the addition by the tail head, each need to traverse the process to obtain a node of a location, the time spent O (n);
The stack can be used, and the same-level nodes of the two linked lists are pressed into the stack sequentially. Then, it pops up and calculates it in turn. This process is actually the same as the function recursive call. This is not a table.
Linked list operation--simulation problem