大整数相加--链表结构正向存储--Add Two Numbers II

来源:互联网 发布:守护小天使app软件 编辑:程序博客网 时间:2024/06/01 20:26
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {        l1=reverse(l1);        l2=reverse(l2);        ListNode* ahead=new ListNode(-1);        ListNode* p=ahead;        int c=0;        int val1,val2;        while(l1||l2)        {            val1=l1==NULL?0:l1->val;            val2=l2==NULL?0:l2->val;            p->next=new ListNode((val1+val2+c)%10);            p=p->next;            c=(val1+val2+c)/10;            l1=l1==NULL?NULL:l1->next;            l2=l2==NULL?NULL:l2->next;        }        if(c==1)        {            p->next=new ListNode(1);        }        return reverse(ahead->next);    }    ListNode* reverse(ListNode* head) {        ListNode* rhead=NULL;        ListNode* p=head;        ListNode* pre=NULL;        while(p)        {            ListNode* pnext=p->next;            if(pnext==NULL)rhead=p;            p->next=pre;            pre=p;            p=pnext;        }        return rhead;    }};

阅读全文
0 0
原创粉丝点击