[Leetcode] 369. Plus One Linked List 解题报告

本文介绍了一种使用递归方法在单链表上实现整数加一的操作。通过递归地遍历链表直到尾部,然后逐位处理进位,最终完成加一的过程。文章详细解释了递归函数的实现思路及代码细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

Example:

Input:
1->2->3

Output:
1->2->4

思路

可以递归实现:如果该结点的下一个结点是空,说明到了链表尾部,就直接加1,并处理进位情况;否则递归调用该结点的下一个节点;如果有进位,则还需要对当前结点进行加1操作,并且最终返回是否在当前位需要进位。注意如果head结点为空需要特殊处理。该算法本身的时间复杂度是O(n),空间复杂度是O(1),但是由于递归调用占用栈空间,所以运行中的时间复杂度是O(n)。

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* plusOne(ListNode* head) {
        if (head == NULL) {
            return new ListNode(1);
        }
        int remain = addOne(head);
        if (remain == 0) {
            return head;
        }
        else {
            ListNode* new_head = new ListNode(1);
            new_head->next = head;
            return new_head;
        }
    }
private:
    int addOne(ListNode* node) {   // precondition: node cannot be NULL
        int remain = 0;
        if (node->next == NULL) {
            if (++node->val >= 10) {
                node->val -= 10;
                remain = 1;
            }
        }
        else {
            node->val += addOne(node->next);
            if (node->val >= 10) {
                node->val -= 10;
                remain = 1;
            }
        }
        return remain;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值