力扣第二题俩数相加-可以直接运行
1 2 3 4 import java.util.ArrayList; 5 6 /** 7 * @author huang. 8 * @version 1.0 9 * @date 2020-5-7 15:02 10 */ 11 class LNode { 12 int var; 13 LNode next; 14 15 public LNode(int x) { 16 var = x; 17 next = null; 18 } 19 20 public static void main(String[] args) { 21 int a[] = {2, 4, 3};//{6}; 22 int b[] = {5, 6, 4};//{7,7,7}; 23 LNode l1 = madeLNode(a); 24 LNode l2 = madeLNode(b); 25 System.out.println(toList(l1)); 26 System.out.println(toList(l2)); 27 System.out.println("-----------------------------------------------"); 28 LNode node = addTwoNumbers(l1, l2); 29 System.out.println(toList(node)); 30 } 31 32 private static LNode addTwoNumbers(LNode l1, LNode l2) { 33 LNode head = new LNode(0); 34 LNode p = l1, q = l2 ,curr = head; 35 //进位 36 int carry = 0; 37 while (p != null || q != null) { 38 int x = (p != null) ? p.var : 0; 39 int y = (q != null) ? q.var : 0; 40 int sum = x+y+carry; 41 carry = sum/10; 42 int value = sum % 10; 43 curr.next = new LNode(value); 44 curr = curr.next; 45 if (q!= null) q =q.next; 46 if (p!= null) p = p.next; 47 } 48 //例如7+8问题,需要进位 49 if (carry>0 ){ 50 curr.next = new LNode(1); 51 } 52 return head.next; 53 } 54 55 private static LNode madeLNode(int[] a) { 56 LNode node = new LNode(a[0]); 57 LNode head = node; 58 59 for (int i = 1; i < a.length; i++) { 60 LNode nodeList = new LNode(a[i]); 61 node.next = nodeList; 62 node = node.next; 63 } 64 return head; 65 } 66 67 private static ArrayList<Integer> toList(LNode node) { 68 ArrayList<Integer> list = new ArrayList<>(); 69 while (node != null) { 70 list.add(node.var); 71 node = node.next; 72 } 73 return list; 74 } 75 }