Algo lab/stack queue codes
ไปยังการนำทาง
ไปยังการค้นหา
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);
}