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;
    }

    每天早上叫醒你的不是闹钟,而是心中的梦~
  • 相关阅读:
    invalid expression: missing ) after argument list in xxx 或者 console.error(("[Vue warn]: " + msg + trace));
    js的alert()
    第9节列表渲染
    第8节条件渲染
    第7节class与style绑定
    CF1215D Ticket Game 博弈论
    CF833A The Meaningless Game 思维
    蚯蚓 队列
    洛谷P2566[SCOI2009]围豆豆
    ants 思维
  • 原文地址:https://www.cnblogs.com/vintion/p/4116876.html
Copyright © 2011-2022 走看看