栈的概念:栈是只允许在一端进行插入和删除操作的线性表(先进后出)
栈顶:栈顶是可以进行插入和删除的那一端
栈底:栈底是固定的,不可以进行插入和删除的操作
空栈:不含任何元素的空表
基本操作代码**(包含顺序栈和链栈)**:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define MaxSize 50
typedef struct
{
int data[MaxSize];
int top;
}Sqstack;
/*====================顺序栈基本操作============================*/
/*
void InitStack(Sqstack &S)
{
S.top = -1;
}
int StackEmpty(Sqstack S)
{
if(S.top == -1)
{
printf("栈空!");
return 1;
}
else
{
printf("栈还未满!");
return 0;
}
}
void Push(Sqstack &S,int x)
{
if(S.top==MaxSize)
{
printf("栈满,无法进栈!");
}
S.top++;
S.data[S.top] = x;
}
void Pop(Sqstack &S,int x)
{
if(S.top==-1)
{
printf("栈空,无法出栈!");
}
x = S.data[S.top--];
}
int GetTop(Sqstack S,int &x)
{
if(S.top==-1)
{
printf("栈空,无法获取栈顶元素!");
return 0;
}
x = S.data[S.top];
return 1;
}
void ClearStack(Sqstack &S)
{
S.top = -1;
}
void Print(Sqstack S)
{
while(S.top>=0)
{
printf("%d ",S.data[S.top--]);
}
}
*/
/*==================链栈的基本操作===========================*/
typedef struct Linknode
{
int data;
struct Linknode *next;
}Linknode,*LinkStack;
void InitLinknode(LinkStack &L)
{
L = (LinkStack)malloc(sizeof(Linknode));
L->next = NULL;
}
int StackEmpty(LinkStack &L)
{
if(L->next == NULL)
{
printf("栈空!");
return 1;
}
return 0;
}
void Push(LinkStack &L,int x)
{
LinkStack p;
p = (LinkStack)malloc(sizeof(Linknode));
p->data = x;
p->next = L->next;
L->next = p;
}
void Pop(LinkStack &L,int &x)
{
if(L->next==NULL)
{
printf("栈空,无法出栈!");
}
LinkStack p;
p = L;
L = L->next;
x = p->data;
free(p);
}
void GetTop(LinkStack &L,int &x)
{
if(L->next==NULL)
{
printf("栈空,无法读取栈顶元素!");
}
x = L->next->data;
}
void ClearStack(LinkStack &L)
{
LinkStack p;
while(L->next!=NULL)
{
p = L;
L = L->next;
free(p);
}
free(L);
}
void Print(LinkStack &L)
{
while(L->next!=NULL)
{
printf("%d ",L->next->data);
L = L->next;
}
}
int main() {
/*
Sqstack S;
InitStack(S);
printf("请输入要存放的元素个数:");
int n;
scanf("%d",&n);
printf("请输入要存放的元素:");
{
int a;
for(int i=0; i<n; i++)
{
scanf("%d",&a);
Push(S,a);
}
}
Print(S);
*/
LinkStack L;
InitLinknode(L);
Push(L,3);
Push(L,4);
Print(L);
return 0;
}