[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:
思路: 只要用一个递归从后往前处理即可, 在最后一个位+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;
}
};
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;
}
};
相关文章推荐
- [Leetcode] 369. Plus One Linked List 解题报告
- [leetcode] 369. Plus One Linked List 解题报告
- [leetCode] 369. Plus One Linked List
- [LeetCode] 369. Plus One Linked List 链表加一运算
- Leetcode 369. Plus One Linked List (Medium) (cpp)
- LeetCode 369. Plus One Linked List(链表加1)
- LeetCode 369. Plus One Linked List
- 【LeetCode】Flatten Binary Tree to Linked List 解题报告
- Leetcode: Plus One Linked List
- LeetCode解题报告—— Linked List Cycle II & Reverse Words in a String & Fraction to Recurring Decimal
- 【LeetCode】Reverse Linked List II 解题报告
- leetcode解题报告(27):Reverse Linked List
- leetcode解题报告(28):Remove Linked List Elements
- LeetCode-Palindrome Linked List-解题报告
- LeetCode "Plus One Linked List"
- 【LeetCode】Flatten Binary Tree to Linked List 解题报告
- [LeetCode] Reverse Linked List II 解题报告
- 【LeetCode】Reverse Linked List 解题报告(Python & java)
- [LeetCode] Flatten Binary Tree to Linked List 解题报告
- 369. Plus One Linked List