[LeetCode]2.两数相加
题目
解法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, cur = 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 = x + y + carry;
carry = sum/10;
cur.next = new ListNode(sum%10);
cur = cur.next;
if(p!=null)p=p.next;
if(q!=null)q=q.next;
}
if(carry > 0){
cur.next = new ListNode(carry);
}
return dummyHead.next;
}
}
参考:https://leetcode-cn.com/problems/add-two-numbers/
总结
可以使用哑点来简化代码,使用变量跟踪进位,要注意链表长短不一的情况.
上面是官方解法,我自己的思路是先判断输入链表长度补全短链表,再进行求和,最后代码冗长…继续刷题吧