当前位置:网站首页>[leetcode] 2. Add two numbers (user-defined listnode), medium
[leetcode] 2. Add two numbers (user-defined listnode), medium
2022-06-27 17:17:00 【ctrl A_ ctrl C_ ctrl V】
1、 subject
Here are two for you Non empty The linked list of , Represents two nonnegative integers . Each of them is based on The reverse Stored in , And each node can only store a Numbers .
Please add up the two numbers , And returns a linked list representing sum in the same form .
You can assume that in addition to the numbers 0 outside , Neither of these numbers 0 start .
【 Example 1 】
Input :l1 = [2,4,3], l2 = [5,6,4]
Output :[7,0,8]
explain :342 + 465 = 807.
【 Example 2 】
Input :l1 = [0], l2 = [0]
Output :[0]
【 Example 3 】
Input :l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output :[8,9,9,9,0,0,0,1]
2、 answer
2.1 Official website answer
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *head = nullptr, *tail = nullptr;
int tab = 0; // carry
while (l1 || l2)
{
int n1 = l1 ? l1->val: 0;
int n2 = l2 ? l2->val: 0;
int sum = n1 + n2 + tab;
tab = sum / 10;
if (!head) // Empty list , Only when the single digit addition is performed for the first time head It's empty .
head = tail = new ListNode(sum % 10);
// Special attention should be paid to the fact that empty linked lists cannot be directly linked to val assignment , Only use new assignment .
else
{
tail->next = new ListNode(sum % 10);
tail = tail->next;
}
if (l1)
l1 = l1->next;
if (l2)
l2 = l2->next;
}
if (tab > 0) // Last carry
tail->next = new ListNode(tab);
return head;
}
};
Although the official answer runs for a long time , Only defeated the whole country 5% Users of . But its algorithm idea is still commendable , The most important idea is to introduce head pointers head And tail pointer tail, In the process of processing, only tail To iterate , Finally back to head, This is much more convenient .
I used only one pointer to do it , When you want to add elements at the end of the linked list, you need to use the pointer from the beginning while Iterate to tail pointer , It will be very troublesome , It's also time-consuming . Or both head and tail It will be much easier to use .
2.2 Simplify the answer
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* head = new ListNode(0), *cur = head;
int tab = 0;
while (l1 || l2)
{
if (l1)
{
tab += l1->val;
l1 = l1->next;
}
if (l2)
{
tab += l2->val;
l2 = l2->next;
}
cur->next = new ListNode(tab % 10);
cur = cur->next;
tab /= 10;
}
if (tab>0)
cur->next = new ListNode(tab);
return head->next;
}
};
Its basic idea is no different from the official answer , Just some simplification , The implementation time has exceeded that of the whole country 60.24% Users of .
3、 Knowledge point
(1) Be familiar with the question mark operator .
(2) Remainder (%) Use :3%10=3,20%10=0,18%10=8
The remainder operation can avoid judgment sum And 10 The size of the relationship .
(3) Custom list LIstNode See my other blog for the operation of C++ Custom one-way linked list ListNode, Use at the same time head and tail Your ideas are well worth learning .
边栏推荐
- Drawing for example study of flashcc
- Source NAT address translation and server mapping web page configuration of firewall Foundation
- Array represents a collection of several intervals. Please merge all overlapping intervals and return a non overlapping interval array. The array must exactly cover all the intervals in the input. 【Le
- How to improve it electronic equipment performance management
- Huawei cloud devcloud launched four new capabilities, setting two domestic firsts
- Oracle概念三
- IDE Eval reset unlimited trial reset
- About how vs2019c # establishes the login interface, the user name and password entered must match the records in the access database
- QT5 之信号与槽机制(信号与槽的基本介绍)
- 软件测试学习-黑马程序员,软件测试学习大纲
猜你喜欢

What is RPC

10分钟掌握mysql的安装步骤

Redis Series 2: data persistence improves availability
![[fxcg] today's market analysis](/img/97/fc6faa5ab693e383f085b407ce1d85.jpg)
[fxcg] today's market analysis

Data center table reports realize customized statistics, overtime leave summary record sharing

Leetcode daily practice (sum of two numbers)

Software testing learning - dark horse programmer, software testing learning outline

关于#mysql#的问题:问题遇到的现象和发生背景

Annual comprehensive analysis of China's audio market in 2022

Unity shadow shadow pancaking
随机推荐
Yyds dry inventory solution sword finger offer: a path with a certain value in the binary tree (3)
【多线程】线程通信调度、等待集 wait() 、notify()
Cloud security daily 220216: root privilege escalation vulnerability found on IBM SaaS integration platform needs to be upgraded as soon as possible
Oracle concept II
简历如何去写?
黑马程序员-软件测试基础班-02-30-45工具代开浏览器运行代码,音、视频、测试点,音视频标签,布局标签。超链接语法进阶,绝对路径,相对路径
The two trump brand products of Langjiu are resonating in Chengdu, continuously driving the consumption wave of bottled liquor
Use pyinstaller to package py files into exe. Precautions and error typeerror:_ get_ sysconfigdata_ name() missing 1...‘ check_ Solutions to exists'
Special function calculator
Pragma once Usage Summary
Construction and management practice of ByteDance buried point data flow
Autodesk NavisWorks 2022 software installation package download and installation tutorial
一个机器人位于一个 m x n 网格的左上角 。机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角。问总共有多少条不同的路径?【LeetCodeHot100】
关于VS2019C#如何建立登陆界面输入的用户名和密码需与Access数据库的记录相匹配
d3dx9_ Where is 35.dll? d3dx9_ Where can I download 35.dll
Part 30 supplement (30) ECMAScript object
数组表示若干个区间的集合,请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。【LeetCodeHot100】
Sword finger offer 22 The penultimate node in the linked list
国家食品安全风险评估中心:不要盲目片面追捧标签为“零添加”“纯天然”食品
Software testing Basics - software testing history, process, classification, benefits, limitations