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 contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
思路,定义两个结点,定义一个整型sum,sum用来相加两个给定的队列的元素,并将值赋给第一个结点,注意如果相加大于10,需要进一(把一保留下来加到下次循环),第二个结点用来保存第二个结点初始时的位置,最后就返回第二个结点即可
package com.RyanWang;
public class AddTwoNumber {
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ListNode l1 = new ListNode(2);
l1.next = new ListNode(4);
l1.next.next = new ListNode(3);
ListNode l2 = new ListNode(5);
l2.next = new ListNode(6);
l2.next.next = new ListNode(4);
ListNode l3;
l3 = addTwoNumbers(l1, l2);
for (; l3 != null; l3 = l3.next) {
System.out.println(l3.val);
}
}
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int sum = 0;
ListNode p, tmp = new ListNode(0);
p = tmp;
while (l1 != null || l2 != null ||sum != 0) {
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
p.next = new ListNode(sum % 10);
sum /= 10;
p = p.next;
}
return tmp.next;
}
}