【1】栈的概念
栈是限制在一端进行插入操作和删除操作的线性表(俗称堆栈),
允许进行操作的一端称为“栈顶”,另一固定端称为“栈底”,当栈中
没有元素时称为“空栈”。
【2】特点 ##
后进先出(LIFO)。
【3】顺序栈(sqstack)
定义数据类型
定义结构体 top = 0, top = -1
创建一个空的栈
判断栈是否为空
判断栈是否为满
入栈(压栈)
出栈(弹栈)
打印栈的数据
【4】链式栈(linkstack)
定义数据类型
定义结构体
创建一个空的栈
判断栈是否为空
入栈(压栈)
出栈(弹栈)
打印栈的数据
【5】代码
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
#define START 1
typedef int datatype_t;
struct sqstack
{
datatype_t data[MAX];
int top;
};
struct sqstack * sqstack_create()
{
struct sqstack *tmp=(struct sqstack *)malloc(sizeof (struct sqstack));
#if START
tmp->top=-1 ;
#else
tmp->top=0 ;
#endif
return tmp;
}
int sqstack_isempty(struct sqstack *ss)
{
#if START
return (ss->top==-1 )?1 :0 ;
#else
return (ss->top==0 )?1 :0 ;
#endif
}
int sqstack_isfull(struct sqstack *ss)
{
#if START
return (ss->top==MAX-1 )?1 :0 ;
#else
return (ss->top==MAX)?1 :0 ;
#endif
}
void sqstack_push(struct sqstack *ss,datatype_t value )
{
if (sqstack_isfull(ss))
{
printf("full\n" );
return ;
}
#if START
ss->data[++(ss->top)]=value ;
#else
ss->data[(ss->top)++]=value ;
#endif
}
datatype_t sqstack_pop(struct sqstack *ss)
{
if (sqstack_isempty(ss))
{
printf("empty\n" );
return -1 ;
}
#if START
return ss->data[(ss->top)--];
#else
return ss->data[--(ss->top)];
#endif
}
void sqstack_print(struct sqstack *ss)
{
int i;
for (i=0 ;i<=ss->top;i++)
{
printf("%d " ,ss->data[i]);
}
putchar(10 );
}
int main()
{
struct sqstack *ss=sqstack_create();
int i;
for (i=0 ;i<5 ;i++)
{
sqstack_push(ss,i);
}
while (sqstack_isempty(ss)==0 )
printf("%d " ,sqstack_pop(ss));
putchar(10 );
free(ss);
return 0 ;
}
#include <stdio.h>
#include <stdlib.h>
typedef int datatype_t;
struct node
{
datatype_t data;
struct node *next;
};
struct node *linkstack_create()
{
struct node *tmp=(struct node *)malloc (sizeof (struct node));
tmp->next=NULL;
return tmp;
}
int linkstack_isempty(struct node *ls)
{
return (ls->next==NULL)?1 :0 ;
}
void linkstack_push(struct node *ls,datatype_t value)
{
struct node *tmp=(struct node *)malloc (sizeof (struct node));
tmp->data=value;
tmp->next=ls->next;
ls->next=tmp;
}
datatype_t linkstack_pop(struct node *ls)
{
if (linkstack_isempty(ls)==1 )
{
printf ("empty" );
return -1 ;
}
struct node *p=ls->next;
ls->next=p->next;
datatype_t tmp=p->data;
free (p);
return tmp;
}
int main()
{
int i;
struct node *linkstack;
linkstack=linkstack_create();
for (i=0 ;i<5 ;i++)
linkstack_push(linkstack,i);
while (linkstack_isempty(linkstack)==0 )
{
printf ("%d " ,linkstack_pop(linkstack));
}
putchar (10 );
return 0 ;
}