标签:interview
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; }
标签:interview
原文地址:http://7371901.blog.51cto.com/7361901/1581732