Problem : https://leetcode.com/problems/plus-one-linked-list/
/**
* 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) {
// reverse list
ListNode reversed = reverse(head);
int carry = 1;
ListNode p = reversed;
ListNode last = null;
while(p != null) {
int total = p.val + carry;
p.val = total % 10;
carry = total / 10;
last = p;
p = p.next;
}
if (carry != 0) {
last.next = new ListNode(carry);
}
return reverse(reversed);
}
ListNode reverse(ListNode head) {
ListNode last = null;
ListNode current = head;
ListNode next = head.next;
while (next != null) {
current.next = last;
last = current;
current = next;
next = current.next;
}
// remember to link the last element!
current.next = last;
return current;
}
}
No comments:
Post a Comment