目录
3.1 栈
3.1.1 栈的定义
1、定义:栈是只允许在一端进行插入或删除操作的线性表。
2、基本概念:
- 栈顶
- 栈底
- 空栈
- 卡特兰数
3、操作特性:后进先出 LIFO
3.1.2 顺序栈
//顺序栈
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 10
typedef struct StackList {
int data[MaxSize];
int top;
}StackList;
//初始化
//栈顶指针初始设为-1,指向栈顶元素;若为0,则指向栈顶元素的下一个元素
bool InitStack(StackList& S)
{
S.top = -1;
return true;
}
//判空
//-1:空栈为-1 0:空栈为0
bool EmptyStack(StackList S)
{
if (S.top == -1)
return true;
else
return false;
}
//判满
//-1:满栈为maxsize-1 0:满栈为maxsize
bool FullStack(StackList S)
{
if (S.top == MaxSize - 1)
return true;
else
return false;
}
//输出栈
bool PrintStack(StackList S)
{
if (EmptyStack(S))
{
printf("the stack is empty!\n");
return false;
}
for (int i = 0; i < S.top + 1; i++)
{
printf("%d\t", S.data[i]);
}
printf("\n");
return true;
}
//入栈
//-1:先top++再赋值 0:先赋值再top++
bool PushStack(StackList& S, int e)
{
if (FullStack(S))
return false;
S.top++;
S.data[S.top] = e;
return true;
}
//出栈
//-1:先赋值然后top-- 0:先top--再赋值
bool PopStack(StackList& S, int& e)
{
if (EmptyStack(S))
return false;
e = S.data[S.top];
S.top--;
return true;
}
//弹出栈顶元素
//-1:S.top 0:S.top--
bool GetTop(StackList S, int& e)
{
if (EmptyStack(S))
return false;
e = S.data[S.top];
return true;
}
int main()
{
StackList S;
InitStack(S);
PushStack(S, 1);
PushStack(S, 55);
PushStack(S, 999);
PushStack(S, 888);
PrintStack(S);
int i=0;
while(i<4)
{
int e=0;
GetTop(S,e);
printf("the top elem is %d\n",e);
PopStack(S,e);
PrintStack(S);
i++;
}
return 0;
}
3.1.3 链栈
//带头结点的链栈
#include <stdio.h>
#include <stdlib.h>
typedef struct SNode{
int data;
struct SNode *next;
}SNode,*LiStack;
//初始化
bool InitStack(LiStack &S)
{
S=(SNode*)malloc(sizeof(SNode));
if(S==NULL)
{
return false;
}
S->next=NULL;
return true;
}
//判空
bool EmptyStack(LiStack S)
{
if(S->next==NULL)
return true;
else
return false;
}
//输出
bool PrintStack(LiStack S)
{
if(EmptyStack(S))
{
printf("the stack is empty\n");
return false;
}
SNode *p=S->next;
while(p!=NULL)
{
printf("%d\t",p->data);
p=p->next;
}
printf("\n");
return true;
}
//进栈
bool PushStack(LiStack &S,int e)
{
SNode *p=(SNode*)malloc(sizeof(SNode));
p->data=e;
p->next=S->next;
S->next=p;
return true;
}
//出栈
bool PopStack(LiStack &S,int &e)
{
if(EmptyStack(S))
{
printf("the stack is empty\n");
return false;
}
SNode *p=S->next;
e=p->data;
S->next=p->next;
free(p);
}
//获取栈顶元素
int GetTop(LiStack S)
{
if(EmptyStack(S))
{
printf("the stack is empty\n");
return false;
}
int s=S->next->data;
return s;
}
int main()
{
LiStack S;
InitStack(S);
PushStack(S,1);
PushStack(S,55);
PushStack(S,666);
PushStack(S,888);
PushStack(S,999);
PrintStack(S);
int i=0;
while(i<5)
{
int e=0;
e=GetTop(S);
printf("the top elem is %d\n",e);
PopStack(S,e);
PrintStack(S);
i++;
}
return 0;
}
3.2 队列
3.2.1 队列的概念
1、队列:只允许在表的一端进行插入,另一端进行删除的线性表,是一种受限的线性表。
2、操作特性:先进先出 FIFO
3、队首、队尾、空队列
3.2.2 顺序队列
1、顺序队列
分配一块连续的存储单元存放队列中的元素,并且设置两个指针front和rear,front指向队首,rear指向队尾元素的下一个位置(也可以指向队尾元素,处理方式不一样)