题目链接: https://leetcode.com/problems/plus-one-linked-list/
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
思路: 只要用一个递归从后往前处理即可, 在最后一个位+1, 然后返回进位值.
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int DFS(ListNode* head)
{
int flag = 0;
if(!head->next) flag = 1;
else flag = DFS(head->next);
int val = head->val+flag;
head->val = val%10;
flag = val/10;
return flag;
}
ListNode* plusOne(ListNode* head) {
if(!head) return head;
if(DFS(head)==0) return head;
ListNode* p = new ListNode(1);
p->next = head;
return p;
}
};