1、题目
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
2、解答: 刚开始还没看明白题目的意思;题目的大概意思是 两个数累加,你可以理解为 7243 + 564这中思想。思想是: 模型加法
3、C++代码:
class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { stack<int> stack1,stack2; while(l1 || l2){ if(l1 != NULL){ stack1.push(l1->val); l1 = l1->next; } if(l2 != NULL){ stack2.push(l2->val); l2 = l2->next; } } int carry = 0; //进位值 ListNode *curr = NULL; while(!stack1.empty() || !stack2.empty()){ int num1 = 0,num2 = 0; if(!stack1.empty()){ num1 = stack1.top(); stack1.pop(); } if(!stack2.empty()){ num2 = stack2.top(); stack2.pop(); } int sum = num1 + num2 + carry; //链表的头插法,以便更好的输出 ListNode *temp = curr; curr = new ListNode(sum % 10); curr->next = temp; carry = sum / 10; } if(carry){ ListNode *temp = curr; curr = new ListNode(carry); curr->next = temp; } return curr; } };
python代码 模型 加法的思想
def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ #该算法的思想是:模型加法 x1,x2 = 0,0 while l1: x1 = x1*10 + l1.val l1 = l1.next while l2: x2 = x2*10 + l2.val l2 = l2.next x = x1 + x2 head = ListNode(0) if x == 0: return head while x: v,x = x%10,x//10 head.next,head.next.next = ListNode(v),head.next #链表的头插法 head = head.next return head