首页 > 代码库 > CC150 2.4

CC150 2.4

2.4 You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list. EXAMPLE Input: (3 -> 1 -> 5) + (5 -> 9 -> 2) Output: 8 -> 0 -> 8


Keep 2 pointers.

Node addUp(Node a, Node b)
{
  Node toReturn = null;
  Node last = null;
  
  boolean shift = false;
  while (a != null || b != null)
  {
      int result = 0;
      if (a != null)
      {
        if (a > 9 || a < 0)
          throw new IllegalArgumentExeption();
          
        result += a.data;
        a = a.next;
      }
      
      if (b != null)
      {
        if (a > 9 || a < 0)
          throw new IllegalArgumentExeption();
          
        result += b.data;
        b = b.next;
      }
      
      if (shift)
        result++;
    
      if (result > 9)
      {
        shift = true;
        result = a % 10;
      }
      else
        shift = false;
        
      Node newNode = new Node(result);
      if (last != null)
      {
        last.next = newNode;
      }
      last = newNode;
        
      if (toReturn == null)
        toReturn = newNode;  
  }
  
  return toReturn;    
}


CC150 2.4