首页 > 其他 > 详细

LeetCode "Plus One Linked List"

时间:2016-06-30 06:22:14      阅读:212      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!