当前位置:网站首页>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;
}
边栏推荐
- Double.doubleToLongBits() method uses
- 怎么加入自媒体,了解这5种变现模式,让账号快速变现
- 不止跑路,拯救误操作rm -rf /*的小伙儿
- Nocalhost - Making development more efficient in the cloud-native era
- Codeforces 862 C. Mahmoud and Ehab and the xor (技巧)
- LAXCUS分布式操作系统安全管理
- 不止跑路,拯救误操作rm -rf /*的小伙儿
- OSSCore 开源解决方案介绍
- 态路小课堂丨如何为CXP光模块选择光纤跳线?
- Do self-media monthly income tens of thousands?Several self-media tools that bloggers are using
猜你喜欢

mysql appears: ERROR 1524 (HY000): Plugin '123' is not loaded

Flutter气泡框实现

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

使用哈工大LTP测试分词并且增加自定义字典

从源码角度分析UUID的实现原理

【勇敢饭饭,不怕刷题之链表】链表反转的几种情况

微信小程序提交审核历史版本记录从哪里查看

怎么加入自媒体,了解这5种变现模式,让账号快速变现

项目部署、

皕杰报表在传参乱码
随机推荐
【勇敢饭饭,不怕刷题之链表】链表中有环的问题
不止跑路,拯救误操作rm -rf /*的小伙儿
学长告诉我,大厂MySQL都是通过SSH连接的
力扣练习——63 找到字符串中所有字母异位词
VSCode远程连接服务器报错:Could not establish connection to “xxxxxx”的可能错误原因及解决
力扣练习——60 二叉搜索子树的最大键值和
Licking Exercise - 60 Maximum key-value sum of binary search subtrees
blocking non-blocking poll mechanism asynchronous
【Untitled】
Chapter 22 Source Code File REST API Reference (4)
机器学习之暴力调参案例
Clicking Exercise - 64 Longest Harmonic Subsequences
LeetCode50天刷题计划(Day 18—— 搜索旋转排序数组(8.50-12.00)
面试官:项目中 Dao、Service、Controller、Util、Model 怎么划分的?
Introduction to Software Architecture
蔚来-软件开发工程师一面记录
LeetCode 138. 复制带随机指针的链表
使用哈工大LTP测试分词并且增加自定义字典
From the product dimension, why can't we fully trust Layer2?
POJ 2891 Strange Way to Express Integers (Extended Euclidean)