题目说明
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.
你被给予2个链接的列表,代表2个非负数。该数字以反向顺序存储,每个节点包含一个数字。把这两个数字加起来,把它作为一个链表。
- Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
- Output: 7 -> 0 -> 8
自己的解法
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int u=0;
int f=0;
int ju=0;
int juge=0;
int i=0;
int s=0;
ListNode a=new ListNode(0);
ListNode head=new ListNode(0);
ListNode q=new ListNode(0);
head.next=q;
ListNode ll1=l1;
ListNode ll2=l2;
ListNode y=l2.next;
ListNode p=l1.next;
while(p!=null){
p=p.next;
i++;
}
while(y!=null)
{
y=y.next;
s++;
}
if(i<=s){
if(i==s)
i++;
if(i<s){
ju=s;
i++;
}
}
else{
juge=i;
i=s;
i++;
}
int []add=new int[i+1];
add[0]=0;
for(int j=0;j<i;j++){
int c=ll1.val+ll2.val;
if(c>=10){
add[j+1]=c/10;
q.val=c%10;
}
else{
q.val=c;
add[j+1]=0;
}
if(j+1>=i)break;
else
{
ListNode t=new ListNode(0);
q.next=t;
q=q.next;
ll1=ll1.next;
ll2=ll2.next;
}
}
q=head.next;
for(int k=0;k<i;k++){
q.val+=add[k];
a=q;
q=q.next;
}
if(add[i]!=0){
ListNode n=new ListNode(0);
n.val=add[i];
a.next=n;
}
if(juge!=0){
for(;f<i;f++)
l1=l1.next;
if(add[i]!=0)
l1.val+=add[i];
a.next=l1;
}
if(ju!=0){
for(;u<i;u++)
l2=l2.next;
if(add[i]!=0)
l2.val+=add[i];
a.next=l2;
}
return head.next;
}
}
- 自己这道题目并没有AC,原因就是想法太简单很多情况没有考虑到。刚开始我让题目所给的测试用例通过了,但是没有考虑到两个链表长度不同的情况,考虑到了长度不同之后,发现又有其他情况无法通过。
Hot解法
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode c1 = l1;
ListNode c2 = l2;
ListNode sentinel = new ListNode(0);
ListNode d = sentinel;
int sum = 0;
while (c1 != null || c2 != null) {
sum /= 10;
if (c1 != null) {
sum += c1.val;
c1 = c1.next;
}
if (c2 != null) {
sum += c2.val;
c2 = c2.next;
}
d.next = new ListNode(sum % 10);
d = d.next;
}
if (sum / 10 == 1)
d.next = new ListNode(1);
return sentinel.next;
}
}
- 看到Hot解法的代码真是自惭形愧,短短的几行代码却解决了,我的70多行代码任无法解决的问题。
感受
- 第一点感受就是题目没有告诉你的条件,不要默认成立。这道题目我一看到测试用例,默认就是两个链表长度相等。
- 第二点感受就是能不要量化的尽量不要量化,像我还将两个链表的长度求出来进行了比较,无形中增加了很多的麻烦。
- 第三点感受就是能放在循环里的操作的尽量都放在循环里操作,不要是总是在循环外面单独将情况拿出来考虑,这样只能说明你的代码没有很好的普遍性。