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.
题意:给出两个链表,每一个链表代表着一个数,要求把两个链表所得到的数相加,得到第三个链表,注意链表的第一个数为这个数的最后一位,没有前导零,除了0本身。
思路:一开始想着把两个链表所表示的数算出来再相加,再转化为链表,然后发现样例中有很大很大的数,只能模拟加法,模拟加法的时候注意进位。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1,ListNode l2) {
//设置一个空节点
ListNode l3 = new ListNode(0),head = l3;
int add = 0,temp;
while(l1 != null && l2 != null) {
if(add + l1.val + l2.val >= 10) {
temp = add + l1.val + l2.val - 10;
add = 1;
}
else {
temp = add + l1.val + l2.val;
add = 0;
}
l3.next = new ListNode(temp);
l3 = l3.next;
l1 = l1.next;
l2 = l2.next;
}
while(l1 != null) {
if(add + l1.val >= 10) {
temp = add + l1.val - 10;
add = 1;
}
else {
temp = add + l1.val;
add = 0;
}
l3.next = new ListNode(temp);
l3 = l3.next;
l1 = l1.next;
}
while(l2 != null) {
if(add + l2.val >= 10) {
temp = add + l2.val - 10;
add = 1;
}
else {
temp = add + l2.val;
add = 0;
}
l3.next = new ListNode(temp);
l3 = l3.next;
l2 = l2.next;
}
if(add == 1) {
l3.next = new ListNode(1);
l3 = l3.next;
add = 0;
}
l3.next = null;
return head.next;
}
}
C语言代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
//ListNode l3 = new ListNode(0),head = l3;
struct ListNode *l3, *head;
l3 = (struct ListNode*)malloc(sizeof(struct ListNode));
head = l3;
int add = 0,temp;
while(l1 != NULL && l2 != NULL) {
if(add + l1 -> val + l2 -> val >= 10) {
temp = add + l1 -> val + l2 -> val - 10;
add = 1;
}
else {
temp = add + l1 -> val + l2 -> val;
add = 0;
}
l3 -> next = (struct ListNode*) malloc(sizeof(struct ListNode));
l3 -> next -> val = temp;
l3 = l3 -> next;
l1 = l1 -> next;
l2 = l2 -> next;
}
while(l1 != NULL) {
if(add + l1 -> val >= 10) {
temp = add + l1 -> val - 10;
add = 1;
}
else {
temp = add + l1 -> val;
add = 0;
}
l3 -> next = (struct ListNode*) malloc(sizeof(struct ListNode));
l3 -> next -> val = temp;
l3 = l3 -> next;
l1 = l1 -> next;
}
while(l2 != NULL) {
if(add + l2 -> val >= 10) {
temp = add + l2 -> val - 10;
add = 1;
}
else {
temp = add + l2 -> val;
add = 0;
}
l3 -> next = (struct ListNode*) malloc(sizeof(struct ListNode));
l3 -> next -> val = temp;
l3 = l3 -> next;
l2 = l2 -> next;
}
if(add == 1) {
l3 -> next = (struct ListNode*) malloc(sizeof(struct ListNode));
l3 -> next -> val = 1;
l3 = l3 -> next;
add = 0;
}
l3 -> next = NULL;
return head -> next;
}