ผลต่างระหว่างรุ่นของ "Algo lab/templates/recursions"
ไปยังการนำทาง
ไปยังการค้นหา
Jittat (คุย | มีส่วนร่วม) |
Jittat (คุย | มีส่วนร่วม) |
||
แถว 26: | แถว 26: | ||
== List processing == | == List processing == | ||
+ | |||
+ | <syntaxhighlight lang="cpp"> | ||
+ | #include <iostream> | ||
+ | |||
+ | struct ListNode | ||
+ | { | ||
+ | int val; | ||
+ | ListNode* next; | ||
+ | |||
+ | ListNode(int val, ListNode* next=0) | ||
+ | : val(val), next(next) {} | ||
+ | }; | ||
+ | |||
+ | int n; | ||
+ | ListNode* first = 0; | ||
+ | ListNode* last = 0; | ||
+ | |||
+ | void read_input() | ||
+ | { | ||
+ | std::cin >> n; | ||
+ | for(int i=0; i<n; i++) { | ||
+ | int x; | ||
+ | std::cin >> x; | ||
+ | if(first == 0) { | ||
+ | first = new ListNode(x); | ||
+ | last = first; | ||
+ | } else { | ||
+ | ListNode* new_node = new ListNode(x); | ||
+ | last->next = new_node; | ||
+ | last = new_node; | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | |||
+ | bool is_empty(ListNode* node) | ||
+ | { | ||
+ | return node == 0; | ||
+ | } | ||
+ | |||
+ | bool is_last(ListNode* node) | ||
+ | { | ||
+ | return node->next == 0; | ||
+ | } | ||
+ | |||
+ | int list_sum(ListNode* node) | ||
+ | { | ||
+ | if(is_empty(node)) { // *** for list_max you might want to change this condition as well | ||
+ | // do something | ||
+ | } else { | ||
+ | // do something | ||
+ | } | ||
+ | } | ||
+ | |||
+ | int main() | ||
+ | { | ||
+ | read_input(); | ||
+ | std::cout << list_sum(first) << std::endl; | ||
+ | } | ||
+ | </syntaxhighlight> |
รุ่นแก้ไขปัจจุบันเมื่อ 04:50, 4 กันยายน 2566
Multiplication / Division
#include <iostream>
int a,b;
int mult(int a, int b)
{
if(b == 0) {
// do something
return 0;
} else {
// do some other things
return 0;
}
}
int main()
{
std::cin >> a >> b;
std::cout << mult(a,b) << std::endl;
}
List processing
#include <iostream>
struct ListNode
{
int val;
ListNode* next;
ListNode(int val, ListNode* next=0)
: val(val), next(next) {}
};
int n;
ListNode* first = 0;
ListNode* last = 0;
void read_input()
{
std::cin >> n;
for(int i=0; i<n; i++) {
int x;
std::cin >> x;
if(first == 0) {
first = new ListNode(x);
last = first;
} else {
ListNode* new_node = new ListNode(x);
last->next = new_node;
last = new_node;
}
}
}
bool is_empty(ListNode* node)
{
return node == 0;
}
bool is_last(ListNode* node)
{
return node->next == 0;
}
int list_sum(ListNode* node)
{
if(is_empty(node)) { // *** for list_max you might want to change this condition as well
// do something
} else {
// do something
}
}
int main()
{
read_input();
std::cout << list_sum(first) << std::endl;
}