leetcode_c++:链表:add two numbers(002)

来源:互联网 发布:mac辣椒红 编辑:程序博客网 时间:2024/05/18 12:28
    *
#include <iostream>#include <vector>#include <map>#include <string>#include <algorithm>#include <cmath>using namespace std;struct ListNode{    int val;    ListNode *next;    ListNode(int x):val(x),next(NULL){}};//尾插法ListNode *addValAndCreateNewNode(ListNode *cur,int val){    cur->val=val;    cur->next=new ListNode(0);    return cur->next;}class Solution{public:    ListNode *addTwoNumbers(ListNode *l1,ListNode *l2){        ListNode *ret=new ListNode(0);        ListNode *cur=ret;        int sum=0;        while(1){            if(l1!=NULL){                sum+=l1->val;                l1=l1->next;            }            if(l2!=NULL){                sum+=l2->val;                l2=l2->next;            }            cur->val=sum%10;  // 该位数字            sum/=10;  //进位数字            if(l1!=NULL || l2!=NULL || sum)                cur=(cur->next=new ListNode(0));   //转入下一个链表节点            else                 break;        }        return ret;    }};int main(){    int t,n;    Solution s;    while (cin>>n) {        ListNode *a = new ListNode(0);        ListNode *b = new ListNode(0);        ListNode *pa=a;        ListNode *pb=b;        while(n--){            cin>>t;            pa=addValAndCreateNewNode(pa,t); //生成链表        }        cin>>n;        while(n--){            cin>>t;            pb=addValAndCreateNewNode(pb,t);        }        s.addTwoNumbers(a,b); //a,b not release!    }    return 0;}
0 0