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

来源:互联网 发布:apache hadoop怎么读 编辑:程序博客网 时间:2024/06/05 21:49

题目

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->3Output: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;    }};

原创粉丝点击