首页 > 其他分享 >leetcode两数之和

leetcode两数之和

时间:2022-12-01 17:07:27浏览次数:51  
标签:ListNode sum next carray l2 l1 leetcode 两数


/**
* 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) {
ListNode *head = nullptr;
ListNode *tail = nullptr;
ListNode *p = nullptr;
int sum = 0;
int carray = 0;
while (l1 != nullptr && l2 != nullptr) {
sum = l1->val + l2->val + carray;
if (sum >= 10) {
carray = 1;
sum -= 10;
}
else {
carray = 0;
}
p = new ListNode(sum);
if (nullptr == head) {
head = p;
}
else {
tail->next = p;
}
tail = p;
l1 = l1->next;
l2 = l2->next;
}
while (l1 != nullptr) {
sum = l1->val + carray;
if (sum >= 10) {
carray = 1;
sum -= 10;
}
else {
carray = 0;
}
p = new ListNode(sum);
tail->next = p;
tail = p;
l1 = l1->next;
}
while (l2 != nullptr) {
sum = l2->val + carray;
if (sum >= 10) {
carray = 1;
sum -= 10;
}
else {
carray = 0;
}
p = new ListNode(sum);
tail->next = p;
tail = p;
l2 = l2->next;
}
if (carray) {
p = new ListNode(carray);
tail->next = p;
}
return head;
}
};

leetcode两数之和_开发

标签:ListNode,sum,next,carray,l2,l1,leetcode,两数
From: https://blog.51cto.com/u_15899033/5902958

相关文章

  • leetcode二叉树遍历
    #include<stdio.h>#include<string.h>#include<iostream>#include<vector>#include<queue>structTreeNode{intval;TreeNode*left;TreeNode*right;......
  • leetcode倒转整数--snprintf性能不行
    #include<stdio.h>#include<string.h>#include<iostream>#include<limits>intreverse(intx){longsum=0;while(x){sum=sum*10+x%10;......
  • leetcode-搜索插入位置
    intsearchInsert(std::vector<int>&nums,inttarget){inti=0;intsize=nums.size();for(;i<size;i++){if(nums[i]>=target){......
  • 设计链表-LeetCode707 基础题
    LeetCode链接:https://leetcode.cn/problems/design-linked-list/题目:设计链表的实现。您可以选择使用单链表或双链表。单链表中的节点应该具有两个属性:val 和 next。val......
  • 力扣02 两数相加
    力扣02两数相加题目:给你两个非空的链表,表示两个非负的整数。它们每位数字都是按照逆序的方式存储的,并且每个节点只能存储一位数字。请你将两个数相加,并以相同形......
  • leetcode 15. 三数之和 js实现
    给你一个整数数组 nums ,判断是否存在三元组 [nums[i],nums[j],nums[k]] 满足 i!=j、i!=k 且 j!=k ,同时还满足 nums[i]+nums[j]+nums[k]==0 。请......
  • LeetCode刷题记录.Day29
    前K个高频元素classSolution{public://小顶堆classmycomparison{public:booloperator()(constpair<int,int>&lhs,constpair<int,......
  • leetcode-160-easy
    IntersectionofTwoLinkedListsGiventheheadsoftwosinglylinked-listsheadAandheadB,returnthenodeatwhichthetwolistsintersect.Ifthetwolinke......
  • leetcode-111-easy
    MinimumDepthofBinaryTreeGivenabinarytree,finditsminimumdepth.Theminimumdepthisthenumberofnodesalongtheshortestpathfromtherootnode......
  • 【LeeCode】2. 两数相加
    【题目描述】给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。请你将两个数相加,并以相同形式返回......