感觉还不错,刷了两道,这一道算是给自己长点信心吧。
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
这道题很简单,相当于一个大数加法,关键点在于指针的操控,以及进位。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int carry = 0;
struct ListNode *p1, *p2;
struct ListNode *result = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode *node = result;
p1 = l1;
p2 = l2;
while (p1 && p2){
node->next = (struct ListNode *)malloc(sizeof(struct ListNode));
node->next->val = (p1->val + p2->val + carry) % 10;
node->next->next = NULL;
if (p1->val + p2->val + carry >= 10)
carry = 1;
else
carry = 0;
p1 = p1->next;
p2 = p2->next;
node = node->next;
}
if (p2)
p1 = p2;
while (p1){
node->next = (struct ListNode *)malloc(sizeof(struct ListNode));
node->next->val = (p1->val + carry) % 10;
node->next->next = NULL;
if (p1->val + carry >= 10)
carry = 1;
else
carry = 0;
p1 = p1->next;
node = node->next;
}
if (carry == 1){
node->next = (struct ListNode *)malloc(sizeof(struct ListNode));
node->next->val = carry;
node->next->next = NULL;
node = node->next;
}
node = result->next;
free(result);
return node;
}
python代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param {ListNode} l1
# @param {ListNode} l2
# @return {ListNode}
def addTwoNumbers(self, l1, l2):
result = ListNode(0)
p = result
carry = 0
while l1 and l2 :
node = ListNode((l1.val + l2.val + carry) % 10)
node.next = None
carry = (l1.val + l2.val + carry) / 10
l1 = l1.next
l2 = l2.next
p.next = node
p = p.next
if l2:
l1 = l2
p.next = l1
while l1:
tmp = (l1.val + carry) % 10
carry = (l1.val + carry) / 10
l1.val = tmp
l1 = l1.next
p = p.next
if carry == 1:
node = ListNode(carry)
node.next = None
p.next = node
result = result.next
return result