ผลต่างระหว่างรุ่นของ "Algo lab/stack queue codes"
ไปยังการนำทาง
ไปยังการค้นหา
Jittat (คุย | มีส่วนร่วม) (→Queue) |
Jittat (คุย | มีส่วนร่วม) |
||
| แถว 1: | แถว 1: | ||
| − | == | + | == Queues == |
<syntaxhighlight lang="c++"> | <syntaxhighlight lang="c++"> | ||
| แถว 57: | แถว 57: | ||
} | } | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | == Stacks == | ||
| + | <syntaxhighlight lang="c++"> | ||
| + | ListNode* front; | ||
| + | |||
| + | void init_stack() | ||
| + | { | ||
| + | front = 0; | ||
| + | } | ||
| + | |||
| + | void push_stack(ValueT v) | ||
| + | { | ||
| + | ListNode* new_node = new ListNode(v,front); | ||
| + | front = new_node; | ||
| + | } | ||
| + | |||
| + | ValueT pop_stack() | ||
| + | { | ||
| + | if(front != 0) { | ||
| + | ValueT v = front->val; | ||
| + | |||
| + | ListNode* new_front = front->next; | ||
| + | delete front; | ||
| + | front = new_front; | ||
| + | |||
| + | return v; | ||
| + | } else { | ||
| + | throw "Error empty stack"; | ||
| + | } | ||
| + | } | ||
| + | |||
| + | ValueT is_stack_empty() | ||
| + | { | ||
| + | return (front == 0); | ||
| + | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
รุ่นแก้ไขปัจจุบันเมื่อ 02:44, 17 กันยายน 2563
Queues
typedef int ValueT;
struct ListNode {
ValueT val;
ListNode* next;
ListNode(ValueT val, ListNode* next=0)
: val(val), next(next) {}
};
ListNode* front;
ListNode* rear;
void init_queue()
{
front = rear = 0;
}
void insert_queue(ValueT v)
{
ListNode* new_node = new ListNode(v);
if(rear != 0) {
rear->next = new_node;
rear = new_node;
} else {
front = rear = new_node;
}
}
ValueT extract_queue()
{
if(front != 0) {
ValueT v = front->val;
ListNode* new_front = front->next;
delete front;
front = new_front;
if(front == 0) {
rear = 0;
}
return v;
} else {
throw "Error extract from empty queue";
}
}
bool is_queue_empty()
{
return (front == 0);
}
Stacks
ListNode* front;
void init_stack()
{
front = 0;
}
void push_stack(ValueT v)
{
ListNode* new_node = new ListNode(v,front);
front = new_node;
}
ValueT pop_stack()
{
if(front != 0) {
ValueT v = front->val;
ListNode* new_front = front->next;
delete front;
front = new_front;
return v;
} else {
throw "Error empty stack";
}
}
ValueT is_stack_empty()
{
return (front == 0);
}