当前位置:网站首页>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;
}
边栏推荐
- 快手“弃”有赞与微盟“结亲”,电商SaaS行业竞争格局将变?
- [Brave food, not afraid to write the linked list] The problem of the penultimate node of the linked list
- LeetCode 82. 删除排序链表中的重复元素 II
- Article take you understand interrupt the key driver of polling mechanism
- HDU 4372:Count the Buildings (Stirling数)
- 【TypeScript】接口类型与类型别名:这两者的用法与区别分别是什么?
- 再有人问你分布式事务,把这篇扔给他
- 实现内网穿透的最佳解决方案(无实名认证,完全免费)
- 【电商运营】你真的了解社交媒体营销(SMM)吗?
- A little self-deprecating deconstruction about farmers "code"
猜你喜欢

LeetCode50天刷题计划(Day 19—— 在排序数组中查找元素的第一个和最后一个位置(9.10-10.40)

基于UiAutomator2+PageObject模式开展APP自动化测试实战

一文带你搞懂中断按键驱动程序之poll机制

接口定义与实现

Weilai-software development engineer side record

LeetCode50天刷题计划(Day 18—— 搜索旋转排序数组(8.50-12.00)

VSCode remote connection server error: Could not establish connection to "xxxxxx" possible error reasons and solutions

mysql出现:ERROR 1524 (HY000): Plugin ‘123‘ is not loaded

L2 applications from a product perspective: why is it a playground?

如何使用工程仪器设备在线监测管理系统
随机推荐
Module 9 - Designing an e-commerce seckill system
机器学习之暴力调参案例
Redis常用命令
基于UiAutomator2+PageObject模式开展APP自动化测试实战
Network sockets (UDP and TCP programming)
LAXCUS分布式操作系统安全管理
StoneDB 文档捉虫活动第一季
LeetCode 61. 旋转链表
HDU 4135:Co-prime (容斥原理)
LeetCode50天刷题计划(Day 19—— 在排序数组中查找元素的第一个和最后一个位置(9.10-10.40)
POJ 3101 Astronomy (Mathematics)
自媒体爆款标题怎么写?手把手教你写热门标题
程序员追求技术夯实基础学习路线建议
Centos7环境使用Mysql离线安装包安装Mysql5.7
不止跑路,拯救误操作rm -rf /*的小伙儿
VSCode remote connection server error: Could not establish connection to "xxxxxx" possible error reasons and solutions
Alibaba最新神作!耗时182天肝出来1015页分布式全栈手册太香了
Article take you understand interrupt the key driver of polling mechanism
rider内Mono脚本找不到引用资源
零基础想自学软件测试,有没有大佬可以分享下接下来的学习书籍和路线?