LeetCode – Plus One Linked List (Java)

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

Java Solution

public ListNode plusOne(ListNode head) {
    ListNode h2 = reverse(head);
 
    ListNode p=h2;
 
    while(p!=null){
        if(p.val+1<=9){
            p.val=p.val+1;
            break;
        }else{
            p.val=0;
            if(p.next==null){
                p.next = new ListNode(1);
                break;
            }
            p=p.next;
        }
    }
 
    return reverse(h2);
}
 
public ListNode reverse(ListNode head){
    if(head==null||head.next==null)
        return head;
 
    ListNode p1=head;
    ListNode p2=p1.next;
    while(p2!=null){
        ListNode t = p2.next;
        p2.next=p1;
        p1=p2;
        p2=t;
    }
 
    head.next=null;
 
    return p1;
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. Abhijeet on 2017-9-6

    private ListNode increment( ListNode head) {
    if (head == null) {
    return head;
    }
    boolean isCarryOver = increment1(head);
    if (isCarryOver) {
    ListNode nhead = new ListNode(1);
    nhead.setNext(head);
    return nhead;
    }
    return head;
    }

    private boolean increment1(ListNode head) {
    boolean isCarryOver = true;
    if (head.getNext() != null) {
    isCarryOver = increment1(head);
    }
    if (isCarryOver) {
    if (head.getValue() < 9) {
    head.setValue(head.getValue() + 1);
    isCarryOver = false;
    } else {
    head.setValue(0);
    }
    }
    return isCarryOver;
    }

  2. Abhijeet on 2017-9-6


    private ListNode increment( ListNode head) {
    if (head == null) {
    return head;
    }
    boolean isCarryOver = increment1(head);
    if (isCarryOver) {
    ListNode nhead = new ListNode(1);
    nhead.setNext(head);
    return nhead;
    }
    return head;
    }

    private boolean increment1(ListNode head) {
    boolean isCarryOver = true;
    if (head.getNext() != null) {
    isCarryOver = increment1(head);
    }
    if (isCarryOver) {
    if (head.getValue() < 9) {
    head.setValue(head.getValue() + 1);
    isCarryOver = false;
    } else {
    head.setValue(0);
    }
    }
    return isCarryOver;
    }

Leave a comment

*