//队列
typedef struct queue_type* Queue;
struct node
{
int val;
struct node* next;
};
struct queue_type
{
struct node* first;
struct node* last;
};
//myStack
typedef struct
{
struct queue_type* q1;
struct queue_type* q2;
}MyStack;
//队列的操作
Queue create(void)
{
Queue q = malloc(sizeof(struct queue_type));
q->first = q->last = NULL;
return q;
}
bool is_empty(Queue q)
{
if (q->first == NULL)
{
return true;
}
else
{
return false;
}
}
void push(Queue q, int n)
{
struct node* new_node = malloc(sizeof(struct node));
new_node->val = n;
new_node->next = NULL;
if (is_empty(q) == true)
{
q->first = q->last = new_node;
}
else
{
q->last->next = new_node;
q->last = new_node;
}
}
int pop(Queue q)
{
int n;
struct node* old_first;
old_first = q->first;
n = old_first->val;
if (q->first == q->last)
{
q->first = q->last = NULL;
}
else
{
q->first = q->first->next;
}
free(old_first);
return n;
}
//mySatck的操作
MyStack* myStackCreate(void)
{
MyStack* myStack = malloc(sizeof(MyStack));
myStack->q1 = create();
myStack->q2 = create();
return myStack;
}
void myStackPush(MyStack* obj, int x)
{
if (is_empty(obj->q1) == true)
{
push(obj->q1, x);
}
else
{
push(obj->q2, x);
while (is_empty(obj->q1) == false)
{
push(obj->q2, pop(obj->q1));
}
while (is_empty(obj->q2) == false)
{
push(obj->q1, pop(obj->q2));
}
}
}
int myStackPop(MyStack* obj)
{
return pop(obj->q1);
}
int myStackTop(MyStack* obj)
{
return obj->q1->first->val;
}
bool myStackEmpty(MyStack* obj)
{
return is_empty(obj->q1);
}
void myStackFree(MyStack* obj)
{
while (is_empty(obj->q1) == false)
{
pop(obj->q1);
}
free(obj->q1);
free(obj->q2);
free(obj);
}
225. 用队列实现栈
最新推荐文章于 2024-06-12 10:00:23 发布