码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Plus One Linked List"

时间:2016-06-30 06:22:59      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
};

LeetCode "Plus One Linked List"

标签:

原文地址:http://www.cnblogs.com/tonix/p/5628732.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!