LeetCode algorithm question: 2. Adding two numbers


Topic description:

You are given two non-empty linked lists, representing two non-negative integers. Each of their digits is stored in reverse order, and each node can only store one digit.

Please add two numbers and return a linked list representing the sum in the same form.

You can assume that except for the number 0, neither number will start with a 0.

题目链接:2. Add two numbers


by code

Create a new linked list:

The advantage is that it is easy to think and operate, but it will increase the storage space occupied. If the data in the linked list itself is large, it will increase the memory consumption.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    
    
        ListNode *first=new ListNode();
        ListNode* p=first,*p1=l1,*p2=l2;
        while(p1||p2){
    
    
            if(p1){
    
    p->val+=p1->val;p1=p1->next;}
            if(p2){
    
    p->val+=p2->val;p2=p2->next;}
            if(p1||p2||p->val>9){
    
    
                p->next=new ListNode();
                if(p->val>9){
    
    
                    p->val-=10; 
                    p->next->val=1;
                }
                p=p->next;
            }
        }
        return first;
    }
};

This is the end

Guess you like

Origin blog.csdn.net/Aer_7z/article/details/132783243