版权声明:本文为博主原创文章,转载请注明出处http://blog.csdn.net/u013132758。 https://blog.csdn.net/u013132758/article/details/51068525
题目
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
说明:
题目的意思是给出两个整数,它们分别倒序存在链表中,将将它们的和也倒序存在链表中返回。
如例子就是求 342 + 465 = 806,将806倒序存储在链表,返回链表。
解题思路:
遍历两个链表,将val相加的值存到l1,flag 变量作为进位,在结束的时候判断是否有进位,有则加上flag。如果最后一个节点有进位的话则需要new一个节点。
代码:
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode L = l1;
ListNode A = new ListNode(0);
A.next = l1;
int flag = 0;
while(l1 != null && l2!= null)
{
l1.val =l1.val +l2.val +flag;
flag = l1.val/10;
l1.val = l1.val % 10;
A = l1;
l1 = l1.next;
l2 = l2.next;
}
if(l2 != null)
{
A.next = l2;
l1 = l2;
}
while (l1 != null) {
l1.val += flag;
flag = l1.val / 10;
l1.val = l1.val % 10;
A = l1;
l1 = l1.next;
}
if (flag > 0) {
ListNode node = new ListNode(1);
A.next = node;
}
return L;
}
}