您的位置:首页 > 其它

Plus One Linked List -- LeetCode

2016-08-27 13:03 323 查看
Given a non-negative number represented as a singly linked list of digits, plus one to the number.

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


思路:递归。

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int help(ListNode* head) {
if (head->next == NULL) head->val++;
else head->val += help(head->next);
if (head->val < 10) return 0;
head->val = 0;
return 1;
}
ListNode* plusOne(ListNode* head) {
int credit = help(head);
if (!credit) return head;
ListNode *res = new ListNode(1);
res->next = head;
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: