Leetcode 369. Plus One Linked List (Medium) (cpp)
Tag: Linked List
Difficulty: Medium
这是一道locked题目,给评论个“赞”呗?
/*
369. Plus One Linked List (Medium)
Given a non-negative number represented as a singly linked list of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
Example:
Input:
1->2->3
Output:
1->2->4
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* plusOne(ListNode* head) {
if (head == NULL) {
return head;
}
ListNode *newhead = reverse(head);
int carry = 1;
for (ListNode *p = newhead; p != NULL && carry != 0; p = p -> next) {
int value = p -> val + carry;
p -> val = value % 10;
carry = value / 10;
}
head = reverse(newhead);
if (carry > 0) {
ListNode *p = new ListNode(1);
p -> next = head;
return p;
}
return head;
}
private:
ListNode* reverse(ListNode* head) {
if (head == NULL || head -> next == NULL) {
return head;
}
ListNode *pre = NULL;
while (head != NULL) {
ListNode *post = head -> next;
head -> next = pre;
pre = head;
head = post;
}
return pre;
}
};