当前位置:网站首页>【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
边栏推荐
猜你喜欢
Personal image bed construction based on Alibaba Cloud OSS+PicGo
GM8775C MIPI转LVDS调试心得分享
Hash table problem solving method
进程(番外):自定义shell命令行解释器
Process (present) : custom shell command line interpreter
实现动态库(DLL)之间内存统一管理
Pylon CLI 低成本的本地环境管控工具应用实例
Comparative analysis of OneNET Studio and IoT Studio
【LeetCode】合并
基础IO(下):软硬链接和动静态库
随机推荐
MC1496乘法器
【LeetCode】设计链表
振芯科技GM8285C:功能TTL转LVDS芯片简介
【LeetCode】Merge
【plang 1.4.4】编写茶几玛丽脚本
剑指Offer 32.Ⅲ从上到下打印二叉树
开源代码交叉编译操作流程及遇到的问题解决(lightdm)
rosdep update失败解决办法(亲测有效)
list:list的介绍和模拟实现
Altium Designer Basics
Introduction and mock implementation of list:list
Comparison between Boda Industrial Cloud and Alibaba Cloud
path 修补文件命令
LT8918L LVDS转MIPI芯片技术支持资料
uniCloud use
【plang 1.4.5】编写坦克(双人)游戏脚本
引擎开发日志:OpenGL资源多线程加载
【面试必看】链表的常见笔试题
NSIS来自己设定快捷方式的图标
使用buildroot制作根文件系统(龙芯1B使用)