当前位置:网站首页>【LeetCode】Add the linked list with carry
【LeetCode】Add the linked list with carry
2022-08-02 05:03:00 【EvilChou】
/*** Definition for singly-linked list.* public class ListNode {* int val;*ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/class Solution {public ListNode addTwoNumbers(ListNode l1, ListNode l2) {ListNode pre = new ListNode(0); //Open up a new memory space, pre points to the memory space, and pre is the head node of the result listListNode cur = pre; //Define a movable pointer that also points to this memory space, and subsequent addition of nodes depends on this pointerint carry = 0; //carrywhile(l1!=null || l2!=null){int x = l1 != null ? l1.val : 0; //Get the value at the corresponding position, if a position is empty, assign it to 0int y = l2 != null ? l2.val : 0;int sum = x + y + carry; //Add the value at the corresponding position of l1 and l2 and the value of the carrycarry = sum / 10; //Get the carry after each additionsum = sum % 10; //Get the value after the carrycur.next = new ListNode(sum); //Create a new node, the value of the node is the value after adding the carry, and the pointer of the resulting linked list points to the nodecur = cur.next; //The result linked list pointer moves forward, the pre head pointer does not moveif(l1!= null){l1 = l1.next;}if(l2!= null){l2 = l2.next;}}if(carry == 1){cur.next = new ListNode(carry); //If there is a carry after the last addition (the carry value must be 1), create a new node and save the node}return pre.next;//Return the result linked list, because pre points to the head pointer of the linked list, the value at the head pointer is 0, and the next node of the head pointer is the first node of the result linked list}}
Open up a new linked list space ListNode pre = new ListNode(0) pre is the head node pointer
The last return is return pre.next, pre.next points to the first node of the result list
Do not use the head node, directly return the result list method
边栏推荐
猜你喜欢
分割回文串 DP+回溯 (LeetCode-131)
Comparative analysis of mobile cloud IoT pre-research and Alibaba Cloud development
bluez5.50+pulseaudio实现蓝牙音响音频播放
联阳IT6561|IT6561FN方案电路|替代IT6561方案设计DP转HDMI音视频转换器资料
Typora use
剑指Offer 16.数值的整数次方 快速幂+ 递归
【plang1.4.3】编写水母动画脚本
idea中创建jsp项目详细步骤
云服务器web项目部署详解
Industry where edge gateway strong?
随机推荐
USB_ID介绍
2020 - AAAI - Image Inpainting论文导读《Learning to Incorporate Structure Knowledge for Image Inpainting》
MC1496乘法器
振芯科技GM8285C:功能TTL转LVDS芯片简介
UKlog.dat和QQ,微信文件的转移
“520” 如何正确地用代码向 ta 表白?
【多线程】线程安全保护机制
与TI的lvds芯片兼容-GM8284DD,GM8285C,GM8913,GM8914,GM8905C,GM8906C,国腾振芯LVDS类芯片,
进程(下):进程控制、终止、等待、替换
【LeetCode】合并
引擎开发日志:OpenGL资源多线程加载
【面试必看】链表的常见笔试题
【操作系统】线程安全保护机制
Hash table problem solving method
使用buildroot制作根文件系统(龙芯1B使用)
所有子字符串中的元音 —— LeetCode - 2063
剑指Offer 34.二叉树中和为某一值的路径 dfs+回溯
云服务器web项目部署详解
【详解】线程池及其自定义线程池的实现
Introduction and mock implementation of list:list