当前位置:网站首页>LeetCode 369. Plus One Linked List(链表加1)
LeetCode 369. Plus One Linked List(链表加1)
2022-08-10 11:09:00 【水菜笔】
给一个链表,表示一个数如123;用链表表示是1->2->3.现在对这个数加一之后返回链表结构;
public ListNode reverseList(ListNode node) {
if (node.next == null) {
return node;
}
ListNode result = reverseList(node.next);
node.next.next = node;
node.next = null;
return result;
}
public ListNode plusOne(ListNode head) {
if (head == null) {
return head;
}
// 先翻转,这样个位数就可以先遍历到
ListNode reverseNode = reverseList(head);
ListNode cur = reverseNode;
int mod = 0;
int add = 1;
while (cur != null) {
// 遍历每一个节点,
int sum = cur.val + add + mod;
cur.val = sum % 10;
mod = sum / 10;
add = 0;
cur = cur.next;
}
// 这里并没有着急拼接余数纯在的情况的节点,反正这个节点也是在第一个,先翻转链表,之后再拼接上。
ListNode result = reverseList(reverseNode);
if (mod != 0) {
ListNode node = new ListNode(1);
node.next = result;
return node;
}
return result;
}
边栏推荐
- 2022年裁员潮,失业程序员何去何从?
- 自媒体爆款标题怎么写?手把手教你写热门标题
- Where can I view the version record of WeChat applet submission review history?
- 项目部署、
- Not just running away, but saving the guy who mishandled rm -rf /*
- Double.doubleToLongBits()方法使用
- Module 9 - Designing an e-commerce seckill system
- 力扣练习——61 根据字符出现频率排序
- AutoCAD Map 3D功能之一暴力处理悬挂点(延伸)
- LCD驱动端与设备端名称匹配过程分析(Tiny4412)
猜你喜欢
英特尔推送20220809 CPU微码更新 修补Intel-SA-00657安全漏洞
Kyligence 通过 SOC 2 Type II 审计,以可信赖的企业级产品服务全球客户
ENVI 5.3软件安装包和安装教程
mysql appears: ERROR 1524 (HY000): Plugin '123' is not loaded
做自媒体月入几万?博主们都在用的几个自媒体工具
The brave rice rice, does not fear the brush list of 】 list has a ring
【勇敢饭饭,不怕刷题之链表】链表倒数节点问题
AUTOCAD - reducing spline curve control points, the advanced CAD practice (3)
Module 9 - Designing an e-commerce seckill system
快手“弃”有赞与微盟“结亲”,电商SaaS行业竞争格局将变?
随机推荐
Programmers pursue technology to consolidate basic learning route suggestions
面试官:项目中 Dao、Service、Controller、Util、Model 怎么划分的?
StoneDB 文档捉虫活动第一季
HDU 1520 Anniversary party (tree dp)
Centos7环境使用Mysql离线安装包安装Mysql5.7
基于UiAutomator2+PageObject模式开展APP自动化测试实战
力扣练习——59 从二叉搜索树到更大和树
皕杰报表在传参乱码
VSCode远程连接服务器报错:Could not establish connection to “xxxxxx”的可能错误原因及解决
APP automation testing practice based on UiAutomator2+PageObject mode
Clicking Exercise - 64 Longest Harmonic Subsequences
做自媒体月入几万?博主们都在用的几个自媒体工具
孩子自律性不够?猿辅导:计划表要注意“留白”给孩子更多掌控感
程序员追求技术夯实基础学习路线建议
Interviewer: How are Dao, Service, Controller, Util, and Model divided in the project?
Double.doubleToLongBits()方法使用
【小程序 | 启航篇】一文打通任督二脉
怎么加入自媒体,了解这5种变现模式,让账号快速变现
基于UiAutomator2+PageObject模式开展APP自动化测试实战
LeetCode 21. 合并两个有序链表