题目链接:https://leetcode.com/problems/add-two-numbers/
题目:
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
解析:题目的意思是有两个链表,每个链表代表一个整数,其中每个节点逆序存放了一个数字,如上图:两个链表表示的数字
是342,465. 相加之后为807,因为存放到链表是逆序,所以为708.
两个链表直接从头到位依次相加即可,若有进位则进位。
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) {
ListNode newHeader = new ListNode(0);
newHeader.next = null;
ListNode tmp = newHeader;
int div = 0;
while(l1 != null && l2 != null){
int val = l1.val + l2.val + div;
div = val/10;
ListNode node = new ListNode(val%10);
node.next = null;
tmp.next = node;
tmp = tmp.next;
l1 = l1.next;
l2 = l2.next;
}
while(l1 != null){
int val = l1.val + div;
div = val/10;
ListNode node = new ListNode(val%10);
node.next = null;
tmp.next = node;
tmp = tmp.next;
l1 = l1.next;
}
while(l2 != null){
int val = l2.val + div;
div = val/10;
ListNode node = new ListNode(val%10);
node.next = null;
tmp.next = node;
tmp = tmp.next;
l2 = l2.next;
}
if(div == 1){
ListNode node = new ListNode(div);
node.next = null;
tmp.next = node;
}
return newHeader.next;
}
}