使用链表模拟了栈,有压栈和弹栈
参照《程序员面试宝典》
#include <stdio.h>
#include <stdlib.h>
typedef struct student
{
int data;
struct student *next;
} node;
typedef struct stakqueue
{
node *bottom,*top;
}queue;
queue *push(queue *HQ,int x)
{
node *s,*p;
s = (node *)malloc(sizeof(node));
s->data = x;
s->next = NULL;
if(HQ->bottom == NULL)
{
HQ->bottom = s;
HQ->top = s;
}
else
{
HQ->top->next = s;
HQ->top = s;
}
return HQ;
}
queue *pop(queue *HQ)
{
node *p;
int x;
if(HQ->bottom == NULL)
printf("
No a node!
");
else
{
x = HQ->bottom->data;
p = HQ->bottom;
if(HQ->bottom == HQ->top)
{
HQ->bottom = NULL;
HQ->top = NULL;
free(p);
}
else
{
while(p->next != HQ->top)
p = p->next;
HQ->top = p;
HQ->top->next = NULL;
free(p->next);
}
}
return HQ;
}
void print(queue *HQ)
{
node *p;
p = HQ->bottom;
printf("||");
while(p != NULL)
{
printf("%d => ",p->data);
p = p->next;
}
printf("
");
}
int main()
{
queue *myst = new queue();
for(int i = 1; i < 6; i++)
{
myst = push(myst,i);
print(myst);
}
for(int i = 1; i < 6; i++)
{
myst = pop(myst);
print(myst);
}
getchar();
return 0;
}