linked list 11

1. Topic 

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. Answer: I didn't understand the meaning of the question at first; the general meaning of the question is the accumulation of two numbers, you can understand it as the idea of ​​7243 + 564. The idea is: model addition


3. C++ code:

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; //carry value
        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;
            //The head insertion method of the linked list for better output
            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;
    }
};

The idea of ​​python code model addition

    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        #The idea of ​​the algorithm is: model addition
        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 #The head insertion method of the linked list
        head = head.next
        return head

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325635725&siteId=291194637