leetcode:445. 两数相加 II(链表)

题目:

在这里插入图片描述

分析:

在这里插入图片描述

使用起来很方便。

代码:

#include<bits/stdc++.h>
using namespace std;
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
int main()
{
 ListNode* l1; 
 stack<int> s1;
 ListNode* l2;
 stack<int> s2;
 if(l1==NULL) return l2;
 if(l2==NULL) return l1;
 while(l1!=NULL)
 {
  s1.push(l1->val);
  l1=l1->next;
 }
 while(l2!=NULL)
 {
  s2.push(l2->val);
  l2=l2->next;
 }
 stack<int> s;
 int cc=0;//进位 
 while(s1.size()!=0||s2.size()!=0)
 {
  int c=0;
  if(!s1.empty())
  {
   c+=s1.top();s1.pop();
  } 
  if(!s2.empty())
  {
   c+=s2.top();s2.pop();
  }
  c+=cc;
  if(c>=10)
  {
   cc=1;c=c%10;
  }
  else cc=0;
  s.push(c);
 }
 if(cc!=0) s.push(1);
 ListNode* l=new ListNode(s.top());
 s.pop();
 ListNode* ll=l;
 while(!s.empty())
 {
  ListNode* ll->next=new ListNode(s.top());
  s.pop();
  ll=ll->next;
 }
 return l;
}
发布了335 篇原创文章 · 获赞 235 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_42721412/article/details/105509600
今日推荐