Thursday, July 14, 2016

Plus One Linked List -- Leetcode

Question:
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

Answer:
public class Solution {
    public ListNode plusOne(ListNode head) {
        boolean flag = Util(head);
        if(flag){
            ListNode newHead = new ListNode(1);
            newHead.next = head;
            return newHead;
        }
        return head;
    }
    
    public boolean Util(ListNode node){
        if(node == null)return true;
        
        ListNode next = node.next;
        //DFS
        boolean flag = Util(next);
        
        if(flag){
           if(node.val == 9){
              node.val = 0;
              return true;
           }else{
              node.val += 1;
           }
        }
        return false;
    }
}

No comments:

Post a Comment