369. Plus One Linked List
2018-01-08 09:45
351 查看
time:2018.01.07
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:
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->3 Output: 1->2->4
用dfs做,dfs返回下一个元素是否有进位,同时如果判断到了最后一个节点,应该将最后一个节点的值进行加一操作。
设置dummynode,在返回过程中判断是否需要需要补0
/** * 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) { ListNode* dummy = new ListNode(0); dummy->next = head; dummy->val = dummy->val + dfs(dummy->next); return dummy->val == 0 ? dummy->next : dummy; } private: int dfs(ListNode* node) { if (node->next == NULL) { node->val++; if (node->val == 10) { node->val = 0; return 1; } else { return 0; } } node->val = node->val + dfs(node->next); if (node->val == 10) { node->val = 0; return 1; } else { return 0; } } };
相关文章推荐
- 369. Plus One Linked List
- Leetcode 369. Plus One Linked List (Medium) (cpp)
- [leetcode] 369. Plus One Linked List 解题报告
- LeetCode 369. Plus One Linked List(链表加1)
- [leetcode] 369. Plus One Linked List 解题报告
- LeetCode 369. Plus One Linked List
- [leetCode] 369. Plus One Linked List
- 369. Plus One Linked List
- [Leetcode] 369. Plus One Linked List 解题报告
- 369. Plus One Linked List
- 369. Plus One Linked List
- [LeetCode] 369. Plus One Linked List 链表加一运算
- LeetCode Plus One Linked List
- Plus One & Plus One Linked List
- Plus One Linked List
- Leetcode: Plus One Linked List
- Plus One Linked List -- LeetCode
- LeetCode "Plus One Linked List"
- Plus One Linked List
- Plus One Linked List