您的位置:首页 > 理论基础 > 数据结构算法

C语言数据结构-顺序栈

2015-10-10 21:40 375 查看

顺序栈

顺序栈为具有特殊运算操作的顺序表,数据通过栈顶先进先出。栈的数据空间和数组类似存储固定的一类数据。存储在连续的空间中,通过出栈和入栈来进行数据操作。

具体看下面的函数实现:

#include <stdio.h>

#define StackSize 20

//定义顺序栈结构
typedef struct{
int data[StackSize];  //栈中数据
int top;   //指示栈顶位置,为-1时栈为空栈
}SeqStack;

//初始化
void InitStack(SeqStack *S)
{
S->top = -1;
}

//栈是否为空
int StackEmpty(SeqStack *S)
{
if(S->top == -1)
return 1;
else
return 0;
}

//栈是否已满
int StackFull(SeqStack *S)
{
if(S->top == StackSize - 1)
return 1;
else
return 0;
}

//数据v压入栈
void Push(SeqStack *S, int v)
{
if(StackFull(S))
printf("Error,the stack is full");
S->data[(++S->top)] = v;
}

//弹出栈顶数据
int Pop(SeqStack *S)
{
int i;
if(StackEmpty(S) == 1)
printf("Error,the stack is empty");
i = S->data[S->top];
S->top--;
return i;
}

int main()
{
SeqStack St;    //这里不能直接声明*St,若声明指针则计算机只会给指针分配内存,而无法为堆栈分配数据存储的空间,因此会报错。
int i = 0;
InitStack(&St);
while(i<=6)           //  将0-6压入栈中
{
Push(&St,i);
i++;
}
printf("The top number of the stack is : %d\n",Pop(&St));    //弹出栈顶元素6
Push(&St,12);
Push(&St,10);
printf("The top number of the stack is : %d\n",Pop(&St));  //弹出栈顶元素10
}


上面的Pop()函数弹出数据是,top会减小,即会使栈改变,在栈的运用中,还有一个常见函数可以读取栈顶数据而不改变栈的内容;它与Pop非常相似,如下:

//读栈顶数据
int Read(SeqStack *S)
{
int i;
if(StackEmpty(S) == 1)
printf("Error,the stack is empty");
i = S->data[S->top];   //读取数据
return i;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 数据结构