[leetcode] 369. Plus One Linked List 解題報告
阿新 • • 發佈:2019-02-07
題目連結: 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; } };