篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 369. Plus One Linked List(Recursive).java相关的知识,希望对你有一定的参考价值。
public class Solution {
public ListNode plusOne(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode i = dummy;
ListNode j = dummy;
while (j.next != null) {
j = j.next;
if (j.val != 9) {
i = j;
}
}
// i = index of last non-9 digit
i.val++;
i = i.next;
while (i != null) {
i.val = 0;
i = i.next;
}
if (dummy.val == 0) return dummy.next;
return dummy;
}
}
/**
* 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(dfs(head)) {
ListNode newHead = new ListNode(1);
newHead.next = head;
return newHead;
} else {
return head;
}
}
private boolean dfs(ListNode head) {
if(head == null) return true;
boolean flag = dfs(head.next);
if(flag) {
int val = head.val + 1;
head.val = val % 10;
return val/10 != 0;
}
return false;
}
}
以上是关于java 369. Plus One Linked List(Recursive).java的主要内容,如果未能解决你的问题,请参考以下文章