2816.cpp (676B)
1 class Solution { 2 static ListNode *rev(ListNode *list) { 3 ListNode *prev = nullptr, *next; 4 while (list) { 5 next = list->next; 6 list->next = prev; 7 prev = list; 8 list = next; 9 } 10 return prev; 11 } 12 13 public: 14 ListNode *doubleIt(ListNode *head) const { 15 head = rev(head); 16 17 ListNode *l = nullptr; 18 int carry = 0; 19 for (ListNode *p = head; p; l = p, p = p->next) { 20 const int val = p->val * 2 + carry; 21 p->val = val % 10; 22 carry = val / 10; 23 } 24 25 if (carry) l->next = new ListNode(carry); 26 27 return rev(head); 28 } 29 };