Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
multiply linked list numbers
//Title of this code #include <iostream> using namespace std; struct node { int data; node* next; node(int d, node* n): data(d), next(n) {} }; node* reverse(node* head) { node* current = head; node* next; node* prev = NULL; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } return prev; } node* multiply(node* head1, node* head2) { node* ret = new node(0, NULL); node* res = ret; node* curRes = ret; node* num1 = head1; while (num1) { curRes = res; int carry = 0; node* num2 = head2; while (num2) { curRes->data += carry + (num1->data * num2->data); if (curRes->data > 9) { carry = curRes->data / 10; curRes->data = curRes->data % 10; } else carry = 0; if (!curRes->next) curRes->next = new node(0, NULL); curRes = curRes->next; num2 = num2->next; } if (carry > 0) curRes->data += carry; num1 = num1->next; res = res->next; } ret = reverse(ret); if (ret->data == 0) { res = ret->next; delete ret; ret = res; } return ret; } void printList(node* head) { while (head) { cout << head->data << ""; head = head->next; } } int main() { node* num1 = new node(9, new node(9, new node(5, new node(9, new node(4, new node(7, NULL)))))); node* num2 = new node(9, new node(7, new node(4, new node(8, new node(9, NULL))))); printList(num1); cout << " * "; printList(num2); cout << " = "; node* numRes = multiply(reverse(num1), reverse(num2)); printList(numRes); }
run
|
edit
|
history
|
help
0
Hangman
VC++ error C2440 with combined use of non-type template parameters
Test
1
Structured Member Value Access Using Structure Member Pointer and Variadic Templates
boost::asyc fail with error C2280: attempting to reference a deleted function
solution_problem4
Error log b is an undeclared identifier...
Time Zone Registry
GetFinalPathNameByHandle Behaviour