一.栈的定义
栈是限定仅在表尾进行插入和删除操作的线性表。我们把允许插入和删除的一端成为栈顶(top),另一端称为栈底(bottom),不含任何数据元素的栈成为空栈。栈又称先进后出的线性表,简称为LIFO(Last In First Out)结构。
栈的插入操作,叫做进栈,也称压栈,入栈。
栈的删除操作,叫做出栈,也称弹栈。
二.栈的链式存储结构
1.链栈的初始化:
首先要定义结构体结点,数据域和指针域,在定义栈的结构体,里面存放栈顶指针和结点的数量,一开始初始化把栈顶指针指向NULL,此时就为空栈,数量为0。
int StackInit(LinkStack *S)
{
S->top = NULL;//S只是一个结构体不需要初始化分配地址,不是结构体指针
S->count = 0;
return SUCCESS;
}
2.进栈操作
int StackPush(LinkStack *S, int e)
{
Node *p = (Node *)malloc(sizeof(Node));//新建一个结点
if(p == NULL)
{
return FAILURE;
}
if(S == NULL)//S是随机分配的一个地址
{
return FAILURE;
}
p->data = e;//把数据赋值给新建结点的数据域
p->next = S->top;//把当前栈顶指针赋给新建结点的指针域形成一条链
S->top = p;//把新建结点的地址赋给栈顶指针
S->count++;//栈中的元素数量加1
return SUCCESS;
}
3.出栈操作
int StackPop(LinkStack *S)
{
if(S == NULL)
{
return FAILURE;
}
Node *p = (Node *)malloc(sizeof(Node));//新建一个结点用来存储要删除的栈顶结点
if(p == NULL)
{
return FAILURE;
}
int e;
p = S->top;//记录栈顶结点
e = S->top->data;将删除的栈顶结点的数据保存到e中
S->top = S->top->next;//栈顶指针向下移动一位
free(p);//释放P
S->count--;//元素数量减1
return e;//返回删除的栈顶元素的值
}
基本操作:
头文件:
#ifndef _LINKSTACK_H_
#define _LINKSTACK_H_
#define SUCCESS 0
#define FAILURE -1
struct node
{
int data;
struct node *next;
};
typedef struct node Node;
struct stack
{
Node *top;//定义栈顶指针
int count;
};
typedef struct stack LinkStack;
int StackInit(LinkStack *S);//栈的初始化
int StackPush(LinkStack *S, int e);//入栈操作
int StackEmpty(LinkStack *S);//判断是否为空栈
int StackGetTop(LinkStack *S);//获取栈顶元素
int StackPop(LinkStack *S);//出栈操作
#endif
主函数:
#include <stdio.h>
#include "LinkStack.h"
int main()
{
int ret, i;
LinkStack stack;
ret = StackInit(&stack);
if(ret == SUCCESS)
{
printf("Init Success!\n");
}
else
{
printf("Init Failure!\n");
}
for(i = 0; i < 5; i++)
{
ret = StackPush(&stack, i);
if(ret == SUCCESS)
{
printf("Push %d Success!\n", i);
}
else
{
printf("Push %d Failure!\n", i);
}
}
ret = StackEmpty(&stack);
if(ret == SUCCESS)
{
printf("The Stack is empty\n");
}
else
{
printf("The Stack is not empty\n");
}
ret = StackGetTop(&stack);
printf("The top is %d\n", ret);
ret = StackPop(&stack);
printf("Pop %d Success!\n", ret);
ret = StackGetTop(&stack);
printf("The top is %d\n", ret);
return 0;
}
各个函数接口:
#include <stdio.h>
#include <stdlib.h>
#include "LinkStack.h"
int StackInit(LinkStack *S)
{
S->top = NULL;
S->count = 0;
return SUCCESS;
}
int StackPush(LinkStack *S, int e)
{
Node *p = (Node *)malloc(sizeof(Node));
if(p == NULL)
{
return FAILURE;
}
if(S == NULL)
{
return FAILURE;
}
p->data = e;
p->next = S->top;
S->top = p;
S->count++;
return SUCCESS;
}
int StackEmpty(LinkStack *S)
{
if(S == NULL)
{
return FAILURE;
}
if(S->count != 0)
{
return FAILURE;
}
return SUCCESS;
}
int StackGetTop(LinkStack *S)
{
if(S == NULL)
{
return FAILURE;
}
return S->top->data;
}
int StackPop(LinkStack *S)
{
if(S == NULL)
{
return FAILURE;
}
Node *p = (Node *)malloc(sizeof(Node));
if(p == NULL)
{
return FAILURE;
}
int e;
p = S->top;
e = S->top->data;
S->top = S->top->next;
free(p);
S->count--;
return e;
}