栈的顺序存储
栈属于线性结构,所以栈的顺序存储和顺序表的顺序存储以及链式储存有点相似。
《大话数据结构》上解释道:栈是限定仅在表尾进行插入和删除操作的线性表
在栈中允许插入和删除的一端称为栈顶,那么另一端称为栈底。栈的操作是先进后出。
来个栈的相关图
栈的顺序存储的结构体的定义
typedef struct
{
SElemType data[MAXSIZE];
int top;
}SqStack;
顺序表的顺序存储结构体定义
typedef struct SqList
{
ElemType data[MAXSIZE]; //变量类型暂时以int型开始
int len;
} SqList;
顺序表的链式存储结构体定义
typedef struct Node
{
ElemType data;
struct Node *next;
}Node;
结合上面三个定义可发现类似之处,栈有顺序表的顺序存储的数组和链式的另一种指针。
代码部分
#include <stdio.h>
#define MAXSIZE 10
typedef char SElemType;
typedef struct
{
SElemType data[MAXSIZE];
int top;
}SqStack;
void Init_Stack(SqStack *s)
{
s->top = -1; //-1 means the stack is empty
}
void Traver_Stack(SqStack s)
{
if (s.top == -1)
{
printf("The stack is empty! \n");
}
else
{
while(s.top != -1)
{
printf("%c ", s.data[s.top]);
s.top--;
}
printf("\n");
}
}
void push_Stack(SqStack *s, SElemType e)
{
if (s->top == MAXSIZE - 1)
{
printf("The stack is full ! \n");
}
else
{
s->top++;
s->data[s->top] = e;
}
}
bool pop_Stack(SqStack *s, SElemType *e)
{
if (s->top == -1)
{
return false;
}
else
{
*e = s->data[s->top];
s->top--;
return true;
}
}
int main()
{
SqStack s;
SElemType e;
Init_Stack(&s);
int option = 1;
printf("\n 1. Initialization stack; \n 2. Traversing stack; \n 3. Push stack; \n 4. Pop stack; \n 0. Exit\n");
while(option)
{
printf("Please enter option to updating the stack: ");
scanf("%d", &option);
switch (option)
{
case 1:
Init_Stack(&s);
break;
case 2:
Traver_Stack(s);
break;
case 3:
printf("Please enter value to be pushed stack: ");
getchar();
scanf("%c", &e);
push_Stack(&s, e);
// Traver_Stack(s);
break;
case 4:
getchar();
if (pop_Stack(&s, &e))
{
printf("The element of poping stack is %c \n", e);
}
else
{
printf("Poping stack is fail ! \n");
}
// Traver_Stack(s);
break;
case 0:
break;
default:
printf("Incorrect operation! Please re-operate!\n");
break;
}
scanf("%*[^\n]%*c");
option = 9;
}
return 0;
}