zoukankan      html  css  js  c++  java
  • 求两个链表结点组成的数之和

    如4->4->6 + 2->4 = 4->7->0
    #include <iostream>
    using namespace std;
    
    typedef struct node{
        int data;
        node *next;
    }node;
    
    node* init(int a[], int n){
        node *head=NULL, *p;
        for(int i=0; i<n; ++i){
            node *nd = new node();
            nd->data = a[i];
            if(i==0){
                head = p = nd;
                continue;
            }
            p->next = nd;
            p = nd;
        }
        return head;
    }
    
    node* addlink(node *p, node *q){
        if(p==NULL) return q;
        if(q==NULL) return p;
        node *res, *pre=NULL;
        int c = 0;
        while(p && q){
            int t = p->data + q->data + c;
            node *r = new node();
            r->data = t%10;
            if(pre){
                pre->next = r;
                pre = r;
            }
            else pre = res = r;
            c = t/10;
            p = p->next; q = q->next;
        }
        while(p){
            int t = p->data + c;
            node *r = new node();
            r->data = t%10;
            pre->next = r;
            pre = r;
            c = t/10;
            p = p->next;
        }
        while(q){
            int t = q->data + c;
            node *r = new node();
            r->data = t%10;
            pre->next = r;
            pre = r;
            c = t/10;
            q = q->next;
        }
        if(c>0){//当链表一样长,而又有进位时
            node *r = new node();
            r->data = c;
            pre->next = r;
        }
        return res;
    }
    
    void print(node *head){
        while(head){
            cout<<head->data<<" ";
            head = head->next;
        }
        cout<<endl;
    }
    
    int main(){
        int n = 4;
        int a[] = {
            1, 2, 9, 3
        };
        int m = 3;
        int b[] = {
            9, 9, 2
        };
    
        node *p = init(a, n);
        node *q = init(b, m);
        node *res = addlink(p, q);
        if(p) print(p);
        if(q) print(q);
        if(res) print(res);
        return 0;
    }

    每天早上叫醒你的不是闹钟,而是心中的梦~
  • 相关阅读:
    直播平台的相关技术(转载)
    各种排序算法分析总结(待整理))
    算法:60.第k个排列
    三种随机化算法:舍伍德算法 拉斯维加斯算法 蒙特卡洛算法
    随机化算法之随机数
    caffe调试
    Euclideanloss_layer层解析
    布线问题(分支限界法)
    最大堆和最小堆
    机器学习知识框架
  • 原文地址:https://www.cnblogs.com/vintion/p/4116876.html
Copyright © 2011-2022 走看看