LeetCode2. Add Two Numbers (linked list operation)

The main idea of ​​the title: Given two lists, sum them in reverse order, and output the sum. Each number in the list specified in the question is non-negative and is a single digit.

Question analysis: The title of this question requires the use of linked lists to operate. It is worth noting that the two lists are not of equal length.

Since I just started to brush the questions of LeetCode, I am not familiar with the programming environment. In LeetCode, some data structures will be implemented well, and we do not need to create them ourselves. have an understanding of the basic operation.

First, declare a head node, the initial value is 0, and then create a list pointer to point to the head node. Why not directly create ListNode * list = new ListNode(0)? Because the head pointer is useful, it needs to return head->next at the end of the function, indicating the first element. In the program, the list pointer, the l1 pointer, and the l2 pointer are always moved, and the head has not been moved. When there is a carry, the carry needs to be counted into the next calculation. At the end, if the highest bit has a carry, a new node is also generated, and the pointer is moved backward, for example, 5+5=10, which needs to be carried by 1.

Code display:

/**
 * 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) {
        int temp = 0;
        ListNode* head = new ListNode(0);
        ListNode* list = head;
        while(l1!=NULL || l2!=NULL){
            if(l1!=NULL){
                temp += l1->val;
                l1 = l1->next;
            }
            if(l2!=NULL){
                temp += l2->val;
                l2 = l2->next;
            }
            list->next = new ListNode(temp%10);
            list = list->next;
            temp /= 10;
        }
        if(temp!=0){
            list->next = new ListNode(temp);
        }
        return head->next;
    }
};

Guess you like

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