We are given two non-null linked list is used to represent two non-negative integer. Among them, in accordance with their respective median is the reverse of the way storage, and they each node can store only one digit. If we add up these two numbers, it will return a new list and to represent them.
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 can assume that in addition to the numbers 0, these two numbers will not begin with 0.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
Problem-solving ideas:
The two lists will traverse the same location node values accumulated and over which a decimal, the relative position of the new list node and the value of whichever bit values. Two lists need to be considered at the same time does not traverse the length of the way, the last one into the need for a linked list traversal is complete.
Java:
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);//虚拟头节点
ListNode cur = head;//指针
int carry = 0;//进位值
while (l1 != null || l2 != null) {//两个链表均为空时停止遍历
int x = (l1 != null) ? l1.val : 0;//x为l1的值,如果节点为空,值为0
int y = (l2 != null) ? l2.val : 0;//y为l2的值,如果节点为空,值为0
int sum = carry + x + y;//sum为两节点值之和
carry = sum / 10;//得进位值(1)
cur.next = new ListNode(sum % 10);//sum%10 得余数即 个位数的值
cur = cur.next;//刷新指针
if (l1 != null) l1 = l1.next;//l1节点不为空继续刷新下一个节点
if (l2 != null) l2 = l2.next;//l2节点不为空继续刷新下一个节点
}
if (carry > 0) {//如果仍然需要进 1 ,则直接新建一个节点
cur.next = new ListNode(carry);
}
return head.next;
}
}
Python3:
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode(0)
cur = head
sum = 0
while l1 or l2:
if l1:#l1不为空
sum += l1.val#累计两节点值的和
l1 = l1.next#刷新节点
if l2:
sum += l2.val#累计两节点值的和
l2 = l2.next#刷新节点
cur.next = ListNode(sum % 10)//刷新新链表
cur = cur.next
sum = sum // 10
if sum != 0:
cur.next = ListNode(sum)
return head.next
Welcome to public attention with the brush No. title: Write Love Bug