作业感受
题目地址: https://leetcode-cn.com/leetbook/read/linked-list/fv6w7/
这个作业其实也不算难,但是自己还是很粗心,在处理进位的时候没有考虑周全,很多边界情况没有考虑到,其实在设置测试用例的时候还是没有用心。是时候给自己列一个checklist啦,就像大神说的,先在纸上写代码,把测试用例写出来,而不是盲目提交。哎,我好像第四次提交才做对,郁闷。
其实这道题一开始想着要转换成ArrayList来着,写了一半发现其实完全就是一个方向往前走吗,链表其实也很方便啦,转换真的是多此一举,及时放弃啦。
作业代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null && l2 == null) return null;
ListNode dummyHead = new ListNode(-1);
ListNode rec = dummyHead;
int carry = 0;
while( l1 != null && l2 != null){
if(carry == 1){
rec.next = new ListNode( (l1.val + l2.val + 1)%10 , null );
rec = rec.next;
if( l1.val + l2.val >= 9) {
carry = 1;
}else{
carry = 0;
}
}else {
rec.next = new ListNode( (l1.val + l2.val)%10, null );
rec = rec.next;
}
if( l1.val+l2.val >= 10) carry =1;
l1 = l1.next;
l2 = l2.next;
}
if( l1 == null) rec.next = l2;
if( l2 == null) rec.next = l1;
while( carry != 0 && rec.next != null) {
rec = rec.next;
if(rec != null){
if(rec.val + 1 <= 9) carry = 0;
rec.val = (rec.val + 1) % 10;
}
if(carry ==1 && rec.next == null) {
rec.next = new ListNode(1,null);
carry = 0;
}
}
if(carry ==1 && rec.next == null)
rec.next = new ListNode(1,null);
return dummyHead.next;
}
}