Thursday 15 May 2014

algorithm - Add to numbers represented by a linked list - Edge case -


I was reading Gaël Lachmann's algorithm on page 108 to list the two numbers linked to the book. If you do not have your book, question, algorithm and code as follows:

question

You have two numbers shown by one linked list, where the single node in each node Points. The digits are deposited in the reverse order, as if the number 1 is at the top of the list. Write a function that adds two numbers and returns the link as a link list.

example

Input: (3-> 1 -> 5), (5-> 9- & gt; 2)

Output: 8-> 0-> 8

algorithm
  1. result.data = (node ​​1 + node 2 + first move)% 10
  2. If node 1 + node2> Linkedlistod Adlist (Linkediston L1, Linked Lists, L2, En) (If (L1 == Blank & L2 == Blank) {Return Null;} LinkedListNode Results = New Linked Lists (Le, Blank, Blank); Int Value = take; if (l1! = Null) {value + = l1.data;} if (l2! = Null) {value + = l2.data;} Result.data = value% 10; Linkediston plus = adl ( L1 == Blank: Blank: l1.next, l2 == Tap? Blank: l2 The obvious thing that comes to mind after looking at the .next, value & gt; 10? 1: 0; result.setNext (more); return result;}

    Is that if (L1 == is blank and L2 == is empty) is that if both digits are zero and there is still a carriage - when we are adding 999 + 99. Does it If there is a right answer, then I fail to see how how can we get the correct answer if it gives wrong answers? The first few lines should be changed to

      linkedaldistodeledlists (Linkedlistod l1, linkedlistodo l2, int lay = zero) {if (l1 == null & amp; L2 == null) {return carry; }   

    What's the trick?

    condition must be:

      value & gt; 9? 1: 0   

    In the following recurring call:

      linkedlistod more = adlists (l1 == empty: tap: l1.next, l2 == tap? Zero: l2.next, value> 10? 1: 0);    

No comments:

Post a Comment