zoukankan      html  css  js  c++  java
  • leetcode-2-两数相加(链表)

    #include<vector>
    #include<map>
    #include<iostream>
    #include<memory>
    using namespace std;
    
    struct ListNode {
        int val;
        ListNode* next;
        ListNode(int x) : val(x), next(NULL) {}
        
    };
    
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        if (l1 == NULL)
            return l2;
        if (l2 == NULL)
            return l1;
        ListNode head(0);
        ListNode* pre = &head;
        int twosum;
        bool carryflag = false;//进位标记位
        while (l1 != NULL && l2 != NULL)
        {
            twosum = l1->val + l2->val + carryflag;
            carryflag = twosum / 10;
            ListNode* p = new ListNode(twosum % 10);
            pre->next = p;
            pre = p;
            l1 = l1->next;
            l2 = l2->next;
        }
        if (l1 != NULL) {
            while (l1 != NULL) {
                ListNode* p;
                if (carryflag) {
                    twosum = l1->val + carryflag;
                    carryflag = twosum / 10;
                    p = new ListNode(twosum%10);
                }
                else
                    p = new ListNode(l1->val);
                pre->next = p;
                pre = p;
                l1 = l1->next;
            }
        }
        else if (l2 != NULL) {
            while (l2 != NULL) {
                ListNode* p;
                if (carryflag) {
                    twosum = l2->val + carryflag;
                    carryflag = twosum / 10;
                    p = new ListNode(twosum%10);
                }
                else
                    p = new ListNode(l2->val);
                pre->next = p;
                pre = p;
                l2 = l2->next;
            }
        }
        if (carryflag) {
            ListNode* p = new ListNode(carryflag);
            pre->next = p;
            pre = p;
        }
        pre->next = NULL;
        return head.next;
    }
    
    void ListTravel(ListNode*p)
    {
        cout << "ADDR(" << p << ")  ";
        while (p != NULL)
        {
            cout << p->val << "	";
            p = p->next;
        }cout << endl;
    }
    
    int main()
    {
        ListNode p1(2), p2(4), p3(3);
        ListNode q1(5), q2(6), q3(4);
        p1.next = &p2; p2.next = &p3; p3.next = NULL;
        q1.next = &q2; q2.next = &q3; q3.next = NULL;
        ListTravel(&p1);
        ListTravel(&q1);
        auto i = addTwoNumbers(&p1, &q1);
        ListTravel(i);
    }
    
  • 相关阅读:
    Android LogCat使用详解
    新时代新潮流WebOS 【20】WebKit的结构与解构
    Android调试的必杀技——反汇编
    真机缺少com.google.android.maps.jar解决方法:
    test
    VMware让ubuntu与win7共享文件方法
    android手机通过笔记本无线wifi上网
    新时代新潮流WebOS 【22】WebKit,鼠标引发的故事
    获取证书
    获取局域网内部机器的MAC地址
  • 原文地址:https://www.cnblogs.com/sgawscd/p/13678558.html
Copyright © 2011-2022 走看看