Plus One Linked List
Question (LC.369)
Analysis
Code
public ListNode plusOne(ListNode head) {
// increment j if less than 9
// increment i if equal to 9, and zero the rest
ListNode dummyNode = new ListNode(0);
dummyNode.next = head;
ListNode leastSig = dummyNode; // if less than 9
ListNode mostSig = dummyNode; // if carry is necessary
// locate leastSig and mostSig
while (leastSig.next != null) {
leastSig = leastSig.next;
if (leastSig.val < 9) mostSig = leastSig;
}
// decide which one to increment
if (leastSig.val < 9) {
leastSig.val ++;
} else {
mostSig.val++;
mostSig = mostSig.next;
while (mostSig != null) {
mostSig.val = 0;
mostSig = mostSig.next;
}
}
// decide which one to return
if (dummyNode.val == 1)
return dummyNode;
return head;
}Last updated