Leetcode 369 Solution
This article provides solution to leetcode question 369 (plus-one-linked-list)
Access this page by simply typing in "lcs 369" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/plus-one-linked-list
Solution
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverse(ListNode* head)
{
ListNode* prev = NULL;
ListNode* p = head;
while (p)
{
auto next = p->next;
p->next = prev;
prev = p;
p = next;
}
return prev;
}
ListNode* addone(ListNode* head)
{
int carry = 1;
ListNode* prev = NULL;
ListNode* p = head;
while (p)
{
p->val += carry;
if (p->val == 10)
{
p->val = 0;
carry = 1;
}
else
{
carry = 0;
break;
}
prev = p;
p = p->next;
}
if (carry == 1 && prev)
prev->next = new ListNode(1);
return head;
}
ListNode* plusOne(ListNode* head)
{
if (head == NULL)
return new ListNode(1);
head = reverse(head);
head = addone(head);
head = reverse(head);
return head;
}
};