首页 > 代码库 > LeetCode题解 || Add Two Numbers 问题

LeetCode题解 || Add Two Numbers 问题

problem:

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

思路:

两个单链表表示的数字相加,再将结果用单链表表示出来,考察链表的基本操作,注意进位即可

注意:

class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
题目给定的两个链表指针l1、l2常理来说指向第一个有效元素,不是指向头结点的指针。因此,返回的指针也是指向有效结点的指针,不是指向头结点。

还有:链表最好使用带头结点的表示方法,方便链表操作!!头结点的数据域无用,随便初始化,用的是其指针域。

代码:

/**
 * 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 flag = 0;
        ListNode* tail = new ListNode(0);
        ListNode* ptr = tail;

        while(l1 != NULL || l2 != NULL){
            int val1 = 0;
            if(l1 != NULL){
                val1 = l1->val;
                l1 = l1->next;
            }

            int val2 = 0;
            if(l2 != NULL){
                val2 = l2->val;
                l2 = l2->next;
            }

            int tmp = val1 + val2 + flag;
            ptr->next = new ListNode(tmp % 10);
            flag = tmp / 10;
            ptr = ptr->next;
        }

        if(flag == 1){
            ptr->next = new ListNode(1);
        }
        return tail->next;
    }
};


LeetCode题解 || Add Two Numbers 问题