I use a stack. Of course you can simply trace nodes with 9s - https://leetcode.com/discuss/111127/iterative-two-pointers-with-dummy-node-java-o-n-time-o-1-space
/** * 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) return nullptr; stack<ListNode*> stk; ListNode *p = head; while(p) { stk.push(p); p = p->next; } int carry = 1; while(!stk.empty() && carry) { int nv = stk.top()->val + carry; stk.top()->val = nv % 10; carry = nv / 10; stk.pop(); } if(!stk.empty() || !carry) return head; ListNode *pnew = new ListNode(1); pnew->next = head; return pnew; } };
时间: 2024-10-03 22:37:36