当用单向链表结构储存堆栈时,top只能位于链表表头,此时插入和删除都很方便,如果top在链表的表尾,那么无法进行删除操作。
1.基本结构
typedef struct SNode *stack;
struct SNode
{
ElementType Data;
struct SNode *Next;
};
2.创建空栈
stack gen()
{
stack s;
s=(stack)malloc(sizeof(stack));
s->Next=NULL;
return s;
}
3.判断是否为空栈
int IsEmpty(stack s)
{
//判断栈是否为空 ,若为空则返回整数1,否则返回0
return (s->Next == NULL);
}
4.入栈
此时栈结构是链式储存,用malloc分配内存,无须验满。
void Push (ElementType item,stack s)
{
stack node;
node=(stack)malloc(sizeof(stack));
node->Data=item;
node->Next=s->Next;
s->Next=node;
}
5.出栈
int Pop(stack s)
{
if(IsEmpty(s))
{
printf("栈空");
return NULL;
}
else
{
int top;
stack p;
top=s->Next->Data;
p=s->Next;
s->Next=p->Next;
free(p);
return top;
}
}