您的位置:首页 > 其它

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

2018-01-16 09:15 591 查看
题目链接: 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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: