问题描述: 给定两个链表,将链表进行反向,然后对两个链表上的各个位置上的数字进行相加进一。将最后结果反向成一链表后输出。
本人解答:代码不够简洁
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode tmp1 = l1;
ListNode tmp2 = l2;
int sum = 0;
int bunus = 0;
ListNode header = new ListNode(0);
ListNode restmp = header;
while(tmp1 != null || tmp2 != null){
if(tmp1 != null && tmp2 != null){
sum = tmp1.val + tmp2.val + bunus;
}else if(tmp1 == null && tmp2 != null){
sum = tmp2.val + bunus;
}else if(tmp1 != null && tmp2 == null){
sum = tmp1.val + bunus;
}
bunus = sum / 10;
int tmpval = bunus > 0 ? sum % 10 : sum;
ListNode newNode = new ListNode(tmpval);
restmp.next = newNode;
restmp = newNode;
try{
tmp1 = tmp1.next;
}catch (NullPointerException e) {
tmp1 = null;
}
try{
tmp2 = tmp2.next;
}catch (NullPointerException e) {
tmp2 = null;
}
}
if(bunus == 1){
ListNode newNode = new ListNode(bunus);
restmp.next = newNode;
restmp = newNode;
}
header = header.next;
return header;
}
leetcode上给出的解答:
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;
}
大体上思路是一致的,创建两个新节点执行当前两个链表,对两个链表上的各个节点进行相加,由于题目要求反向相加后进行反向输出,由于链表的性质,实际上就可以直接省略反向这一步骤。在链表节点相加的过程中,对进位的进行记录然后最后进行判断是否还有进位标志,如果有则说明由最后一个节点。链上链表后输出即可。