1 题外话
我又回来更新Leetcode了,现在准备有空做做leetcode,等着用java刷完以后再切换到其他语言试试吧~~。
2 题目理解
[原题](https://leetcode.com/problems/add-two-numbers/)
原题的理解很简单,毕竟这是一道不太难的Medium难度的题。
首先检查输入的链表是否为空,不为空才能继续,一个为空的话返回不为空的就好了(leetcode挺喜欢检查边界或特殊情形呢,小心)。随后分别用两个指针指向两个输入链表的当前节点,求和运算后生成一个新的ListNode,并连接到结果立案表上。
这题需要注意的就是:进位的运算,和最后一个数字运算后的进位,最后的一个运算容易忘了运算,如99+1=100,多了一位,特别小心.
3 原题
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Subscribe to see which companies asked this question
4 解法(Java)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//处理边界条件
if(l1 == null)
return l2;
if(l2 == null)
return l1;
//构造头结点,和当前节点p
ListNode head = new ListNode(-1);
ListNode p= head;
//进位表示
int carry = 0;
//构造操作数 形成a+b+carry=c,然后根据c确定是否进位
int a,b,c;
//开始构造,只要有一个不为空就可以继续
while(l1!=null || l2!=null){
a=b=0; //首先需要初始化所有值
if ( l1 != null){
a=l1.val;
l1=l1.next;
}
if ( l2 != null){
b=l2.val;
l2=l2.next;
} //运算处理进位
c=a+b+carry;
p.next = new ListNode(c % 10);
carry = c / 10;
p=p.next;
}
//注意这里需要进位
if (carry == 1) {
p.next = new ListNode(1);
}
head=head.next; //头部是多余的
return head;
}
}
注意的是,我的不算是(我自己的)最优解法,针对链表,其实当其中一个遇到空的时候,其实就能省略一部分运算,直接连接,而给出的代码则是还傻傻的走下去。。
有空的话,再做改进吧。。毕竟这些都是几天前写的,屯着慢慢发
最后有问题请:点这里 点这里 看这里 看这里 关注这里 关注这里:)