LeetCode 369. 给单链表加一
题目描述
给定一个用链表表示的非负整数, 然后将这个整数 再加上 1 。
这些数字的存储是这样的:最高位有效的数字位于链表的首位 head 。
示例 1:
输入: head = [1,2,3]
输出: [1,2,4]
链表中的节点数在 [1, 100] 的范围内。
0 <= Node.val <= 9
由链表表示的数字不包含前导零,除了零本身。
一、解题关键词
二、解题报告
1.思路分析
1、遍历
2、全局变量累加
3、递归计算
2.时间复杂度
3.代码示例
/**
* 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 plusOne(ListNode head) {
//遍历
helper(head);
if(carry != 0){
return new ListNode(carry,head);
}
return head;
}
int carry = 0;
void helper(ListNode head){
if(null == head){
return;
}
if(head.next == null){
carry = (head.val + 1) / 10;
head.val = (head.val + 1) % 10;
return;
}
helper(head.next);
int sum = head.val + carry;
head.val = sum % 10;
carry = sum / 10;
}
}
2.知识点