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

369. Plus One Linked List

时间:2016-11-20 07:00:18      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:represent   ber   index   last   link   val   public   nod   its   

Given a non-negative number represented as a singly linked list of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

Example:

Input:
1->2->3

Output:
1->2->4

ListNode* plusOne(ListNode* head) {
        ListNode *l1 = reverse(head);
        ListNode* cur = l1, *nh = NULL;
        int c = 1;
        while (cur != NULL) {
            cur->val += c;
            c = cur->val / 10;
            cur->val %= 10;
            cur = cur->next;
        }
        l1 = reverse(l1);
        
        if (c != 0) {
            nh = new ListNode(c);
            nh->next = l1;
            l1 = nh;
        }
        return l1;
    }
    
    ListNode* reverse(ListNode* head) {
        ListNode* prev = NULL;
        ListNode* cur = head;
        ListNode* nxt = NULL;
        while (cur != NULL) {
            nxt = cur->next;
            cur->next = prev;
            prev = cur;
            cur = nxt;
        }
        return prev;
    }
public class Solution {
// two pointer
    public ListNode plusOne(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode i = dummy;
        ListNode j = dummy;

        while (j.next != null) {
            j = j.next;
            if (j.val != 9) {
                i = j;
            }
        }
        // i = index of last non-9 digit
    
        i.val++;
        i = i.next;
        while (i != null) {
            i.val = 0;
            i = i.next;
        }
        
        if (dummy.val == 0) return dummy.next;
        return dummy;
    }
}

 

369. Plus One Linked List

标签:represent   ber   index   last   link   val   public   nod   its   

原文地址:http://www.cnblogs.com/fripside/p/6082003.html

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