Open yokostan opened 5 years ago
Stack solution only 12% faster:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode plusOne(ListNode head) {
ListNode p = head;
Stack<ListNode> stk = new Stack<>();
while (p != null){
stk.push(p);
p = p.next;
}
while (!stk.isEmpty()){
ListNode cur = stk.pop();
if (cur.val != 9){
cur.val = cur.val + 1;
return head;
}
cur.val = 0;
}
ListNode newHead = new ListNode(1);
newHead.next = head;
return newHead;
}
}
dummy node is one position ahead of the head with 0 as its value, so we are able to either return 1000 or 899 according to whether head value has been carried or not.