Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
List Add v3
//Title of this code #include <iostream> using namespace std; struct node { int num; node* next; node(int num, node* next) { this->num = num; this->next = next; } }; void print(node* n) { while(n) { cout << n->num << " "; n = n->next; } cout << endl; } int node_to_num(node *n) { int num = n->num; node *cur = n->next; while (cur) { num = (num * 10) + cur->num; cur = cur->next; } return (int)num; } node* num_to_node(int num) { node *n = NULL; while (num > 0) { n = new node(num % 10, n); num /= 10; } return n; } node* node_add(node* n1, node* n2) { int num1 = node_to_num(n1); int num2 = node_to_num(n2); return num_to_node(num1 + num2); } // [1] -> [2] -> [3] -> [4] -> [] // [] <- [1] <- [2] <- [3] <- [4] node* reverse(node* n) { node *perv = NULL; node *cur = n; node *next = n->next; if (next) while (cur) { cur->next = perv; perv = cur; if (next) { cur = next; next = cur->next; } else { break; } } return cur; } node* node_add2(node* n1, node* n2) { n1 = reverse(n1); n2 = reverse(n2); node *n = NULL; int carry = 0; while (n1 || n2) { int num1, num2; if (n1) { num1 = n1->num; n1 = n1->next; } else num1 = 0; if (n2) { num2 = n2->num; n2 = n2->next; } else num2 = 0; num1 += num2 + carry; if(num1 > 9) { carry = 1; num1 -= 10; } else { carry = 0; } n = new node(num1, n); } if (carry) n = new node(carry, n); return n; } int main() { node *n1 = new node(9, new node(9, new node(9, NULL))); node *n2 = new node(9, new node(9, new node(9, NULL))); //n1 = reverse(n1); //print(n1); //print(n2); //node *n = node *n = node_add2(n1, n2); print(n); //cout << node_to_num(n); }
run
|
edit
|
history
|
help
0
integerDivision
project
QP
diamond
ThreadContext
Simple use of function templete and namespace
decode
process memory structure
CirclQ
How to make stupid to my friend?