小编太不容易了,大家给小编点一点赞
typedef int DataType;
typedef struct QNode
{
struct QNode* next;
DataType val;
}QNode;
typedef struct Queue//避免老是传二级指针
{
QNode* phead;
QNode* tail;
int size;
}Queue;
int QSize(Queue* p)
{
assert(p);
return p->size;
}
bool QueueEmpty(Queue* p)
{
assert(p);
if (p->size == 0)
return true;
else
return false;
}
void QueueInit(Queue* p)
{
assert(p);
p->phead = p->tail = NULL;
p->size = 0;
}
DataType QueueFront(Queue* p)
{
assert(p);
assert(p->phead);
return p->phead->val;
}
DataType QueueBack(Queue* p)
{
assert(p);
assert(p->tail);
return p->tail->val;
}
void QueueDestroy(Queue* p)
{
assert(p);
QNode* cur = p->phead;
while (cur)
{
QNode* next = cur->next;
free(cur);
cur = next;
}
p->phead = p->tail = NULL;
p->size = 0;
}
void Qpop(Queue* p)
{
assert(p);
assert(p->size);
if (p->phead->next ==NULL)
{
free(p->phead);
p->phead = p->tail = NULL;
}
else
{
QNode* next = p->phead->next;
free(p->phead);
p->phead = next;
}
p->size--;
}
//
typedef struct {
Queue p1;
Queue p2;
} MyStack;
MyStack* myStackCreate() {
MyStack* pst = (MyStack*)malloc(sizeof(MyStack));
QueueInit(&pst->p1);
QueueInit(&pst->p2);
return pst;
}
void QPush(Queue* p, DataType x)//插入先创建空间
{
assert(p);
QNode* newNode = (QNode*)malloc(sizeof(QNode));
if (newNode == NULL)
{
printf("malloc failed");
return;
}
newNode->next = NULL;
newNode->val = x;
if (p->phead == NULL)
{
p->phead = p->tail = newNode;
}
else
{
p->tail->next = newNode;
p->tail = newNode;
}
p->size++;
}
void myStackPush(MyStack* obj, int x) {
if (!QueueEmpty(&obj->p1))
{
QPush(&obj->p1, x);
}
else
{
QPush(&obj->p2,x);
}
}
int myStackPop(MyStack* obj)
{
Queue* Empty = &obj->p1;
Queue* NonEmpty = &obj->p2;
if (!QueueEmpty(&obj->p1))
{
Empty = &obj->p2;
NonEmpty = &obj->p1;
}
while (QSize(NonEmpty) > 1)
{
QPush(Empty, QueueFront(NonEmpty));
Qpop(NonEmpty);
}
DataType top = QueueFront(NonEmpty);
Qpop(NonEmpty);
return top;
}
int myStackTop(MyStack* obj) {
if (!QueueEmpty(&obj->p1))
{
return QueueBack(&obj->p1);
}
else
{
return QueueBack(&obj->p2);
}
}
bool myStackEmpty(MyStack* obj) {
return QueueEmpty(&obj->p1) && QueueEmpty(&obj->p2);
}
void myStackFree(MyStack* obj) {
QueueDestroy(&obj->p1);
QueueDestroy(&obj->p2);
free(obj);
}