Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
    }
};
posted on 2016-06-30 01:53  Tonix  阅读(258)  评论(0编辑  收藏  举报