注意进位的处理和节点为null的处理
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int flag = 0; ListNode res = null; ListNode temp = null; //注意如果进位不是0的话还要添加一个节点 while (l1!=null||l2!=null||flag!=0) { int cur = flag; flag = 0; if (l1!=null) { cur+=l1.val; l1 = l1.next; } if (l2!=null) { cur+=l2.val; l2 = l2.next; } if (cur>9) { flag = 1; cur%=10; } if (res==null) { res = new ListNode(cur); temp = res; continue; } temp.next = new ListNode(cur); temp = temp.next; } return res; }
原文地址:https://www.cnblogs.com/stAr-1/p/8436632.html
时间: 2024-10-29 02:38:18