[LeetCode] Plus One Linked List

369. Plus One Linked List

Given a non-negative integer represented as a linked list of digits, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list.

  • recursive solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
int solution(ListNode* node) {
if(!node) return 1;
int append = solution(node->next);
node->val += append;
if(node->val == 10) {
node->val = 0;
return 1;
}
return 0;
}
public:
ListNode* plusOne(ListNode* head) {
int append = solution(head);
if(append)
head = new ListNode(1, head);
return head;
}
};
  • iterative solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* plusOne(ListNode* head) {
ListNode* node = head;
vector<ListNode*> st;
while(node) {
st.push_back(node);
node = node->next;
}
int append = 1;
while(!st.empty() && append) {
st.back()->val += append;
if(st.back()->val == 10) {
st.back()->val = 0;
append = 1;
} else append = 0;
st.pop_back();
}

if(append)
head = new ListNode(1, head);
return head;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/19/PS/LeetCode/plus-one-linked-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.