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

369. Plus One Linked List

时间:2016-12-03 15:10:46      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:out   ini   represent   sign   eve   its   output   link   turn   

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

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode plusOne(ListNode head) {
        if(head == null) return head;
        ListNode l = new ListNode(0);
        ListNode dummy = l;
        ListNode reHead = reverseList(head);
        int carry = 1;
        int digit = 0;
        ListNode cur = reHead;
        while(cur != null || carry != 0){
            int index = (cur == null)?  0 : cur.val ;
            digit = (index + carry) % 10;
            carry = (index + carry) / 10;
            l.next = new ListNode(digit);
            l = l.next;
            if(cur != null)
                cur = cur.next;
        }
        return reverseList(dummy.next);
    }
    public ListNode reverseList(ListNode head){
        if(head == null || head.next == null) return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode cur = head.next;
        while(cur != null){
            head.next = cur.next;
            cur.next = dummy.next;
            dummy.next = cur;
            cur = head.next;
        }
        return dummy.next;
    }
}

 

369. Plus One Linked List

标签:out   ini   represent   sign   eve   its   output   link   turn   

原文地址:http://www.cnblogs.com/joannacode/p/6128383.html

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