题目详情
我的开始代码解析
这个代码是简单实现版,没有追求代码的精简。
package com.ke.leetCodes;
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
//Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
//Output: 7 -> 0 -> 8
//Explanation: 342 + 465 = 807.
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1==null) return l2;
if(l2==null) return l1;
ListNode t1 = l1;
ListNode t2 = l2;
ListNode result = null;
ListNode head = null;
int carry = 0;
int data = 0;
while(t1!=null&&t2!=null){
data = (t1.val+t2.val+carry)%10;
carry = (t1.val+t2.val+carry)/10; //进位
ListNode current = new ListNode(data);
if(result == null) {
result = current;
head = result;
}else{
result.next = current;
result = result.next;
}
t1 = t1.next;
t2 = t2.next;
}
while(t1!=null){
data = (t1.val+carry)%10;
carry = (t1.val+carry)/10; //进位
ListNode current = new ListNode(data);
if(result == null) {
result = current;
head = result;
}else{
result.next = current;
result = result.next;
}
t1 = t1.next;
}
while(t2!=null){
data = (t2.val+carry)%10;
carry = (t2.val+carry)/10; //进位
ListNode current = new ListNode(data);
if(result == null) {
result = current;
head = result;
}else{
result.next = current;
result = result.next;
}
t2 = t2.next;
}
if(carry!=0){
ListNode current = new ListNode(carry);
result.next = current;
result = result.next;
}
return head;
}
//Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
//Output: 7 -> 0 -> 8
//Explanation: 342 + 465 = 807.
public static void main(String[] args) {
// int [] a1 = new int[]{2,4,3};
// int [] a2 = new int[]{5,6,4};
int [] a1 = new int[]{1};
int [] a2 = new int[]{9,9};
ListNode l1 = null;
ListNode l2 = null;
ListNode h1 = null;
ListNode h2 = null;
for(int i = 0;i<a1.length;i++){
if(l1 == null){
h1 = new ListNode(a1[i]);
l1= h1;
}else{
h1.next = new ListNode(a1[i]);
h1 = h1.next;
}
}
for(int i = 0;i<a2.length;i++){
if(l2 == null){
h2 = new ListNode(a2[i]);
l2 = h2;
}else{
h2.next = new ListNode(a2[i]);
h2 = h2.next;
}
}
print(l1);
print(l2);
Solution obj = new Solution();
Solution.print(obj.addTwoNumbers(l1, l2));
}
public static void print(ListNode l){
ListNode tl= l;
while(tl!=null){
System.out.print(tl.val+" ");
tl=tl.next;
}
System.out.println();
}
}
精选答案
如果不看别的大神写的代码,永远都不会提高:
答案。
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
return dummyHead.next;
}
可以从参考答案中借鉴的点
- 将表头直接新建了个值为0的节点,这样保证头结点是可以直接next,而不抛空指针异常。
- 循环语句的精简:既然都是一遍大循环,为什么循环不能用在一个里面呢?
- 最后的进位,仍然要进行判断,如果有进位,要再新加一个节点,进行链接。