元宵已过,这还是大学以来第一次在家过元宵,之前家里一直有客人,小孩不断啊...所以,电脑基本无缘了,但是现在可以自由使用了...
之前放假回来拿了本《算法导论》,回来就真当是放假了,没怎么看,这下继续往后看...
如题,基本数据结构,话说当时学习《数据结构》时没好好学啊,后来也一直在补,对这方面也比较重视。
第一期:亡羊补牢犹未晚啊,栈,按照书上小小的操作一下,后续会有补充...
栈和队列都是动态集合,且在其上进行DELETE操作所移除的元素是预先设定的。在栈(stack)中,被删除的是最近插入的元素:即栈实现的是一种后进先出(last-in,first-out,LIFO)策略。
下面是栈的简单操作,即初始化InitStack,空栈StackEmpty,入栈Push,出栈Pop;
#include<iostream>
using namespace std;
const int StackMaxSize = 30; //栈空间
typedef int ElemType; // 定义元素类型为整型
typedef struct Stack
{
ElemType stack[StackMaxSize]; //栈
int top;
}STACK;
void InitStack(Stack &S)
{
S.top = 0;
}
bool StackEmpty(Stack S) //判断空栈
{
if(S.top == 0)
return true;
else
return false;
}
void Push(Stack &S, int x) //压栈
{
if(S.top == StackMaxSize)
return;
S.top++;
S.stack[S.top] = x;
}
int Pop(Stack &S) //出栈,并返回此时栈顶元素
{
if(S.top == 0)
return -1;
S.top--;
return S.stack[S.top];
}
int main()
{
STACK S;
InitStack(S);
if(StackEmpty(S))
cout<<"栈为空"<<endl;
else
cout<<"非空栈"<<endl;
Push(S, 15);
Push(S, 6);
Push(S, 2);
Push(S, 9);
cout<<Pop(S)<<endl;
cout<<Pop(S)<<endl;
return 0;
}
第二期:栈-2
由于ElemType stack[StackMaxSize],栈的坐标是从下标0开始的:
#include<iostream>
using namespace std;
const int StackMaxSize = 4; //栈空间
typedef int ElemType; // 定义元素类型为整型
typedef struct Stack
{
ElemType stack[StackMaxSize]; //栈
int top;
}STACK;
void InitStack(Stack &S)
{
S.top = -1;
}
bool StackEmpty(Stack S) //判断空栈
{
if(S.top == -1)
return true;
else
return false;
}
void Push(Stack &S, int x) //压栈
{
if(S.top == StackMaxSize - 1)
return;
S.top++;
S.stack[S.top] = x;
}
int Pop(Stack &S) //出栈,并返回此时栈顶元素
{
if(S.top == -1)
return -1;
S.top--;
if(S.top > -1)
return S.stack[S.top];
else
cout<<"已是空栈"<<endl;
return 0;
}
int main()
{
STACK S;
InitStack(S);
if(StackEmpty(S))
cout<<"栈为空"<<endl;
else
cout<<"非空栈"<<endl;
Push(S, 15);
Push(S, 6);
Push(S, 2);
Push(S, 9);
cout<<Pop(S)<<endl;
cout<<Pop(S)<<endl;
cout<<Pop(S)<<endl;
cout<<Pop(S)<<endl;
return 0;
}
将StackMaxsize改为4,在进行初始化时,top = -1;当入栈的时候,与StackMaxsize - 1比较,判断是否满了,出栈同样;
运行如下:
后续遇到会继续补上...
*∩_∩*