题目:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
思路:
题目内容为以链表输出两个链表反向相加的结果,一开始的思路是先将两个链表恢复成反向存储的整数,将两数求和后,再取反存在链表中,循环较多,计算量大,同时提交不成功,后发现可以从两个链表的开头依次两两相加,如果和大于9,向右侧进一位。
代码:
/**
* 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) {
//正着加反着加一样
//curr用于存放当前结果
ListNode l3 = new ListNode(0);
ListNode curr = l3,p = l1,q = l2;
int x = 0,y = 0,i = 0,sum = 0;
while( p != null || q != null){
x = (p != null) ? p.val : 0;
y = (q != null) ? q.val : 0;
sum = x + y + sum;
curr.next = new ListNode(sum%10);
curr=curr.next;
sum = sum / 10;
if(p != null) p = p.next;
if(q != null) q = q.next;
}
//当最后一位两两相加的和大于9时,向最右侧再进一位
if(sum != 0){
curr.next = new ListNode(sum);
}
return l3.next;
}
}