0369. Plus One Linked List
Description
**Input:** head = [1,2,3]
**Output:** [1,2,4]**Input:** head = [0]
**Output:** [1]ac1: recursive
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode plusOne(ListNode head) {
boolean hasCarry = helper(head);
if (hasCarry) {
ListNode h = new ListNode(1);
h.next = head;
return h;
}
return head;
}
private boolean helper(ListNode node) {
// exit
if (node == null) return true;
boolean hasCarry = helper(node.next);
if (hasCarry) {
if (node.val == 9) {
node.val = 0;
return true;
} else {
node.val++;
return false;
}
}
return false;
}
}ac2: iterative
Last updated