当前位置:网站首页>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;
}
边栏推荐
猜你喜欢
基于UiAutomator2+PageObject模式开展APP自动化测试实战
【勇敢饭饭,不怕刷题之链表】链表倒数节点问题
实现内网穿透的最佳解决方案(无实名认证,完全免费)
模块九 - 设计电商秒杀系统
StoneDB Document Bug Hunting Season 1
老板加薪!看我做的WPF Loading!!!
即时零售业态下如何实现自动做账?
学长告诉我,大厂MySQL都是通过SSH连接的
【勇敢饭饭,不怕刷题之链表】链表反转的几种情况
[Brave food, not afraid of the linked list of brushing questions] Merging of ordered linked lists
随机推荐
Intel pushes 20220809 CPU microcode update to patch Intel-SA-00657 security vulnerability
Double.doubleToLongBits() method uses
Nocalhost - Making development more efficient in the cloud-native era
flask-restplus接口地址404问题
使用.NET简单实现一个Redis的高性能克隆版(六)
Do self-media monthly income tens of thousands?Several self-media tools that bloggers are using
LeetCode 92. 反转链表 II
【机器学习】浅谈正规方程法&梯度下降
英特尔推送20220809 CPU微码更新 修补Intel-SA-00657安全漏洞
力扣练习——61 根据字符出现频率排序
Flutter气泡框实现
常量及数据类型你还记得多少?
【勇敢饭饭,不怕刷题之链表】有序链表的合并
程序员追求技术夯实基础学习路线建议
Not just running away, but saving the guy who mishandled rm -rf /*
【TypeScript】接口类型与类型别名:这两者的用法与区别分别是什么?
基于UiAutomator2+PageObject模式开展APP自动化测试实战
从脚本到剪辑,影像大师亲授的后期制作秘籍
Pulling drills - 56 Finding the right interval
LeetCode50天刷题计划(Day 19—— 在排序数组中查找元素的第一个和最后一个位置(9.10-10.40)