source: https://leetcode.com/problems/plus-one-linked-list/description/
Plus One Linked List
Given a non-negative integer represented as a linked list of digits, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list.
Example 1:
Input: head = [1,2,3]
Output: [1,2,4]
Example 2:
Input: head = [0]
Output: [1]
Constraints:
The number of nodes in the linked list is in the range [1, 100].
0 <= Node.val <= 9
The number represented by the linked list does not contain leading zeros except for the zero itself.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode plusOne(ListNode head) { int carry = dfs(head); if(carry==1){ ListNode node = new ListNode(1); node.next = head; head = node; //print(head); return head; } return head; } public int dfs(ListNode node){ if(node==null){ return 1; } int i = dfs(node.next); if(i==1){ int sum = node.val + 1; node.val = sum%10; return sum/10; } return 0; } private void print(ListNode node){ while(node!=null){ System.out.print(node.val+"->"); node = node.next; } } } |