题目
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
分析:
从起点一直加进去,难度不大。
c++实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
ListNode *p1, *p2, *pr = NULL, *phead = NULL;
p1 = l1;
p2 = l2;
while(p1 != NULL || p2 != NULL){
if(pr == NULL){
//cout<< "new point"<<endl;
pr = (ListNode*) malloc(sizeof(ListNode));
phead = pr;
pr->val = 0;
}
else {
//cout<< "next point"<<endl;
pr->next = (ListNode*) malloc(sizeof(ListNode));
if(pr->val >= 10){
pr->val -= 10;
pr->next->val = 1;
}
else
pr->next->val = 0;
pr = pr->next;
}
if(p1 != NULL){
pr->val += p1->val;
p1 = p1->next;
}
if(p2 != NULL){
pr->val += p2->val;
p2 = p2->next;
}
}
if(pr->val >= 10){//
pr->next = (ListNode*) malloc(sizeof(ListNode));
pr->val -= 10;
pr->next->val = 1;
pr = pr->next;
}
pr->next = NULL;
return phead;
}
};
python 实现
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 is None: return l2
if l2 is None: return l1
last_node = node = None
muil = 0
while l1 is not None and l2 is not None:
cur_node, muil = self.addNodeValue(muil, l1.val+l2.val)
if node is None:
node = cur_node
if last_node != None:
last_node.next = cur_node
last_node = cur_node
l1 = l1.next
l2 = l2.next
if l1 is None:
l1 = l2
while l1 is not None:
if muil == 0:
last_node.next = l1
break
cur_node, muil = self.addNodeValue(muil, l1.val)
last_node.next = cur_node
last_node = last_node.next
l1 = l1.next
if muil == 1:
last_node.next = ListNode(muil)
return node
def addNodeValue(self, muil, val):
num = muil + val
if num < 10:
return ListNode(num), 0
else:
return ListNode(num-10), 1