LeetCode_Add Two Numbers
2024-08-27 15:28:11
题目:
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路:计算进位,注意最后一位的处理。
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
{
if(l1 == NULL || l2 == NULL)
{
return l1==NULL?l2:l1;
}
ListNode *head = l1; int len1 = 0;
int len2 = 0; ListNode *p1 = l1;
ListNode *p2 = l2; while(p1!=NULL)
{
len1++;
p1=p1->next;
}
while(p2!=NULL)
{
len2++;
p2=p2->next;
}
//cout<<len1<<";"<<len2<<endl;
ListNode *pre_l1 = l1;
ListNode *pre_l2 = l2; int jinwei = 0; while(l1!=NULL && l2!=NULL)
{
int sum = l1->val + l2->val + jinwei;
l1->val = sum%10;
//计算进位
if(sum>=10)
{
jinwei = 1;
}
else
{
jinwei = 0;
}
pre_l1 = l1;
l1 = l1->next;
pre_l2 = l2;
l2 = l2->next;
}
if(l1==NULL&&l2!=NULL)
{
pre_l1->next = l2;
while(l1==NULL&&l2!=NULL)
{
int sum = l2->val + jinwei;
l2->val = sum%10;
if(sum>=10)
{
jinwei = 1;
}
else
{
jinwei = 0;
}
pre_l2 = l2;
l2 = l2->next;
}
}
if(l2==NULL&&l1!=NULL)
{
while(l2==NULL&&l1!=NULL)
{
int sum = l1->val + jinwei;
l1->val = sum%10;
if(sum>=10)
{
jinwei = 1;
}
else
{
jinwei = 0;
}
pre_l1 = l1;
l1 = l1->next;
}
}
if(jinwei == 1 && len1>=len2)
{
ListNode *end = new ListNode(jinwei);
//找到最后的节点
pre_l1->next = end;
}
if(jinwei == 1 && len1<len2)
{
ListNode *end = new ListNode(jinwei);
//找到最后的节点
pre_l2->next = end;
}
return head;
}
int main(void)
{
//cout<<"l"<<endl;
ListNode *l1 = new ListNode(2);
ListNode *l2 = new ListNode(4);
ListNode *l3 = new ListNode(3);
l1->next = l2;
l2->next = l3;
ListNode *l11 = new ListNode(5);
ListNode *l21 = new ListNode(6);
ListNode *l31 = new ListNode(2);
l11->next = l21;
l21->next = l31; ListNode *p = addTwoNumbers(l1,l11);
while(p!=NULL)
{
cout<<p->val<<" ";
p=p->next;
}
delete l1;
delete l2;
delete l3;
delete l11;
delete l21;
delete l31;
system("pause");
return 0;
}
最新文章
- 笔记本中的archlinux调节亮度
- VIM常用设置
- Tree:加载列表数据
- upload控件上传json文件合并的两种方法
- shell中 ";"; 跟 &#39;&#39;的区别
- yum info 查不到nginx下载info的问题
- C#中ListView的简单使用方法
- 正则的小效果:------->; 过滤敏感词
- css required,focus,valid和invalid介绍
- Hadoop的奇技淫巧
- LocalActivityManager的内部机制
- java集合的互转
- Intention Locks 意向锁
- java 显示目录下全部文件
- Java数据结构与算法(5) - ch05链表(LinkList)
- BZOJ 1337: 最小圆覆盖1336: [Balkan2002]Alien最小圆覆盖(随机增量法)
- 实时通讯系列目录篇之SignalR详解
- deepin 下安装goland中文字体显示全是方块
- 2331: [SCOI2011]地板 插头DP
- hadoop核心逻辑shuffle代码分析-map端
热门文章
- Makefile 11——支持头文件目录指定
- JavaScript概述.pdf
- lscpu和cat /proc/cpuinfo
- Insubstantial 6.2 Release
- [JS] 页面回车键提交表单-常用于登录页面
- DTD与XML Schema都是XML文档。(选择1项)
- JAVA中有一个特殊的类: Object
- scanner, BufferedReader, InputStreamReader 区别及特殊字符的输入
- jQuery学习笔记2——表单操作
- 【BZOJ】1672: [Usaco2005 Dec]Cleaning Shifts 清理牛棚(dp/线段树)