Plus One Linked List Posted on 2018-11-09 Descriptionhttps://leetcode.com/problems/plus-one-linked-list/ Solution123456789101112131415161718192021222324252627282930313233343536373839404142/** * 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) { if (head == NULL) return head; ListNode* cur = new ListNode(0); ListNode* ret = cur; cur->next = head; while(cur->next) { stack<ListNode*> st; st.push(cur); //The digit before the leading 9 while(cur->next && cur->next->val == 9) { cur = cur->next; st.push(cur); } if(cur->next == NULL) { //The last digit is 9 while(st.size() > 1) { ListNode* item = st.top(); st.pop(); item->val = 0; } st.top()->val += 1; return ret->val ? ret : ret->next; } //Find the next 9 while(cur->next && cur->next->val != 9) cur = cur->next; } //The last digit is not 9 cur->val += 1; return ret->next; }};