Question:
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
題目意思:
兩個數(shù)字鏈表形式給出,求和
代碼如下:
答題思路,將兩個鏈表存放到兩個數(shù)組中去,缺失的高位用0填補,每次計算類似加法器,設(shè)置一個進位計數(shù)器carry,每次取相應(yīng)位于進位計數(shù)器相加求得相應(yīng)數(shù)值與下一個進位,最后需要對進位進行判斷,如果大于0則再加一位。
<pre>
/**
Definition for singly-linked list.
struct ListNode {
int val;struct ListNode *next;-
};
/
struct ListNode addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int length1 = 0;
struct ListNode* p1 = l1;
while(p1 != NULL) {
length1++;
p1 = p1->next;
}int length2 = 0;
struct ListNode* p2 = l2;
while(p2 != NULL) {
length2++;
p2 = p2->next;
}int length = length1 > length2 ? length1 : length2;
int arr1[length];
int arr2[length];
for(int i = 0; i < length; i++) {
arr1[i] = 0;
arr2[i] = 0;
}p1 = l1;
for(int posi1 = length - length1; posi1 <= length -1; posi1++) {
arr1[posi1] = p1->val;
p1 = p1->next;
}p2 = l2;
for(int posi2 = length - length2; posi2 <= length -1; posi2++) {
arr2[posi2] = p2->val;
p2 = p2->next;
}int carry = 0;
int plus = 0;
struct ListNode* ans = NULL;
for(int i = length;i >= 1; i--) {
plus = (arr1[i-1] + arr2[i-1] + carry)%10;
carry = (arr1[i-1] + arr2[i-1] + carry)/10;
struct ListNode* temp = (struct ListNode*)malloc(sizeof(struct ListNode));
temp->val = plus;
temp->next = ans;
ans = temp;
}struct ListNode* head = NULL;
if(carry != 0) {
head = (struct ListNode*)malloc(sizeof(struct ListNode));
head->val = carry;
head->next = ans;
}else {
head = ans;
}
return head;
}
</pre>
吐槽下:lettcode為什么不支持int a[3] = {0}的初始化方式,= =,戰(zhàn)戰(zhàn)兢兢想著默認會是0,結(jié)果不是= =
看了排行第一的解答= = 先把鏈表翻轉(zhuǎn)= =然后該干啥干啥
我簡直是個弱智