leetcode Add Two Numbers VS 2010

来源:互联网 发布:空巢老人最新数据 编辑:程序博客网 时间:2024/06/08 01:58
<div class="question-title"><h3 style="display: inline;">Add Two Numbers</h3>           <span class="total-ac text-info">Total Accepted: <strong>31985</strong></span>           <span class="total-submit text-info">Total Submissions: <strong>139983</strong></span>           <a target=_blank class="pull-right btn btn-default" href="https://oj.leetcode.com/problems/add-two-numbers/submissions/">My Submissions</a>                     <div class="pull-right btn-group right-pad"><button class="btn btn-default active" type="button">Question</button>                           <button disabled="disabled" class="btn btn-default" type="button"> Solution </button>                       </div></div><div class="row"><div class="col-md-12"><div class="question-content"><p></p><p>You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.</p><p style="font-family: monospace;"><strong>Input:</strong> (2 -> 4 -> 3) + (5 -> 6 -> 4)<strong>Output:</strong> 7 -> 0 -> 8</p></div></div></div>
#include<iostream>#include<string>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) {        int sum=0;        ListNode *h = new ListNode(0);//解决什么问题???!!!很重要的啊!头指针保护        ListNode *r = h;        while(l1 != NULL || l2 != NULL){            sum /= 10;            if(l1 != NULL){                sum += l1->val;                l1 = l1->next;            }            if(l2 != NULL){                sum += l2->val;                l2 = l2->next;            }            r->next = new ListNode(sum%10);            r = r->next;                    }        if(sum/10 == 1)            r->next = new ListNode(1);        return h->next;            }};int main(){ListNode *l1=new ListNode(0),*l2=new ListNode(0),*res=NULL;ListNode *l1h = l1,*l2h = l2;int *t1,*t2,n,m;cin >> n;t1 = new int[n];for(int i=0;i<n;i++){cin >> t1[i];if(l1 == NULL)l1 = new ListNode(t1[i]);else{l1->next = new ListNode(t1[i]);l1 = l1->next;}}cin >> m;t2 = new int[m];for(int i=0;i<m;i++){cin >> t2[i];if(l2 == NULL)l2 = new ListNode(t2[i]);else{l2->next = new ListNode(t2[i]);l2 = l2->next;}}Solution tg;res = tg.addTwoNumbers(l1h->next,l2h->next);do{cout<<res->val<<endl;res = res->next;}while(res != NULL);system("pause");return 0;}
写测试真心不容易啊!要考虑好多问题,但是最终还是做出来了,要注意头的指针怎么保护,就是 <pre name="code" class="cpp">ListNode *l1=new ListNode(0) 然后<span style="font-family: Arial, Helvetica, sans-serif;">l1h->next。切记,然后怎么建立链表。</span>
<span style="font-family: Arial, Helvetica, sans-serif;"></span>

0 0
原创粉丝点击