LeetCode Add Two Numbers(用链表模拟加法)

来源:互联网 发布:idc联想数据 编辑:程序博客网 时间:2024/06/17 20:51

题目链接:

传送门

Code:

#include <bits/stdc++.h>using namespace std;struct ListNode {    int val;    ListNode *next;    ListNode(int x) : val(x), next(NULL) {}};class Solution {public:    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {        ListNode *head=NULL,*p=NULL;        int val=0;        while(l1!=NULL||l2!=NULL||val){            int left=val;            if(l1!=NULL){                left+=l1->val,l1=l1->next;            }            if(l2!=NULL){                left+=l2->val,l2=l2->next;            }            val=left/10;            left=left%10;            ListNode* tmp = new ListNode(left);            if(!head)                head=tmp;            if(p)                p->next=tmp;            p=tmp;        }        return head;    }};int main(){    ListNode *l1,*l2,*l3;    l1=new ListNode(99);    l3=new ListNode(99);    Solution fuck;    ListNode *ans = fuck.addTwoNumbers(l1,l3);    while(ans!=NULL){        cout<<ans->val;        ans=ans->next;    }    puts("");    return 0;}
1 0
原创粉丝点击