Plus One Linked List
Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
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
Solution
/**
* 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 new ListNode(1);
if (head.next == null) {
if (head.val < 9) {
head.val += 1;
return head;
} else {
head.val = 0;
ListNode node1 = new ListNode(1);
node1.next = head;
return node1;
}
}
ListNode reverseNode = reverseLinkedList(head);
int carry = 1;
ListNode runner = reverseNode;
while (runner.next != null) {
int current = runner.val;
int total = current + carry;
runner.val = total % 10;
carry = total / 10;
runner = runner.next;
}
if (carry == 1 && runner.val == 9) {
runner.val = 0;
ListNode node1 = new ListNode(1);
runner.next = node1;
} else {
runner.val += carry;
}
return reverseLinkedList(reverseNode);
}
private ListNode reverseLinkedList(ListNode node) {
if (node == null) return null;
if (node.next == null) return node;
ListNode next = node.next;
ListNode reverse = reverseLinkedList(next);
next.next = node;
node.next = null;
return reverse;
}
}