• day1<两数相加> pboost


    题目描述:

     

    #include <iostream>
    #include <vector>
    #include <map>
    using namespace std;
    
    struct ListNode {
        int val;
        ListNode *next;
        ListNode() : val(0), next(NULL) {}
        ListNode(int x) : val(x), next(NULL) {}
        ListNode(int x, ListNode *next) : val(x), next(next) {}
     };
    
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode * head , *result;
            head = result = new ListNode(0);
            int temp = 0;
    
            while(l1 || l2 || temp)
            {
                if(l1 != NULL)
                {
                    temp += l1->val;
    
                }
                if(l2 != NULL)
                {
                    temp += l2->val;
                }
    
    
                ListNode * q = new ListNode(temp % 10);
                result->next = q;
                result = result->next;
    //            cout << result->val << " ";
                temp = temp / 10;
                if(l1 != NULL)
                {
                    l1 = l1->next;
                }
                if(l2 != NULL)
                {
                    l2 = l2->next;
                }
            }
            return head->next;
        }
    };
    
    void printValue(ListNode* L)
    {
        while (L!=NULL)
        {
            cout << L->val << " ";
            L = L->next;
        }
    }
    
    int main()
    {
        ListNode* l1, *l2, *head1, *head2, *q;
        Solution S;
        l1 = head1 = new ListNode;
        l2 = head2 = new ListNode;
    
        int n;
        cin >> n;
        for(int i = 0;i < n;++i)
        {
            int temp = 0;
            cin >> temp;
            q = new ListNode;
            q->val = temp;
            l1->next = q;
            l1 = l1->next;
        }
        l1->next = NULL;
    
        for(int i = 0;i < n;++i)
        {
            int temp = 0;
            cin >> temp;
            q = new ListNode;
            q->val = temp;
            l2->next = q;
            l2 = l2->next;
        }
        l2->next = NULL;
    
        ListNode* l3 = S.addTwoNumbers(head1,head2);
        if(l3 == NULL)
        {
            cout << "什么也不是" << endl;
        }
        printValue(l3->next);
    
    
        return 0;
    }

     心得:

    调试了好久,后来发现这几行特别重要:

    if(l1 != NULL)
                {
                    l1 = l1->next;
                }
                if(l2 != NULL)
                {
                    l2 = l2->next;
                }

    没有加if判断句的话,程序会发生执行错误!

    head = result = new ListNode(0);
    这一行也很重要,初始化值为0,要不然也会出错,这个是节点初始化的意思、
  • 相关阅读:
    POJ 1995
    POJ 3233
    HDU 2815
    POJ 2417
    POJ 3243
    HDU 3579 线性同余方程组
    HDU 1573
    POJ 2115
    POJ 2891
    HDU 2035 不忍直视的水
  • 原文地址:https://www.cnblogs.com/boost/p/16307498.html
Copyright © 2020-2023  润新知