0
点赞
收藏
分享

微信扫一扫

栈的表示和操作的实现

潇湘落木life 2022-04-03 阅读 82
数据结构

顺序栈的表示和实现(一个完整的例子)

#include<bits/stdc++.h>
using namespace std;
//顺序栈的表示和实现
#define MAXSIZE 100 //分配的存储空间
typedef int ElemType;
typedef  int Statue;

typedef struct {
    ElemType data[MAXSIZE] ;//存放栈中元素
    int top; //栈顶指针
} SqStack;

void InitStack(SqStack &S); //初始化
bool StackEmpty(SqStack S);//判断栈是否空
bool Push(SqStack &S,ElemType x);//进栈
bool Pop(SqStack &S,ElemType &e);//出栈
bool GetTop(SqStack S, ElemType &e);//读栈顶元素
Statue StackLength(SqStack S);//获取栈的长度
void Print_s(SqStack S);//遍历栈

int main() {
    SqStack s;
    InitStack(s);
    Push(s,5);
    Push(s,1);
    Push(s,8);
    Print_s( s);
    int e;
    Pop(s,e);
    cout<<"出栈"<<e<<endl;
    Print_s(s);
    cout<<StackEmpty(s)<<endl;
}
void Print_s(SqStack S) {
    while(S.top!=-1) {
        cout<<S.data[S.top--];
    }
    cout<<endl;
}
Statue StackLength(SqStack S) {
    return ++S.top;
}
bool GetTop(SqStack S, ElemType &e) {
    //读栈顶元素
    if(S.top==-1)
        return false;
    e = S.data[S.top];
    return true;
}
bool Pop(SqStack &S,ElemType &e) {
    //出栈
    if(S.top==-1)
        return false;//栈空报错
    e=S.data[S.top--];//先出栈,指针再减1
    return true;
}
bool Push(SqStack &S,ElemType x) {
    //进栈
    if(S.top==MAXSIZE-1) //栈满
        return false;
    S.data[++S.top]=x; //等价于 S.top=S.top+1;S.data[S.top]=x
    return true;
}
bool StackEmpty(SqStack S) {
    //判断是否为空
    if(S.top==-1)
        return true;
    else
        return false;
}
void InitStack(SqStack &S) {
    //初始化
    S.top = -1 ;//初始化栈顶指针
}

链栈

//存储结构
typedef struct Linknode{
	ElemType data; //数据域
	struct Linknode *next;	//指针域
}*LinkStack,StackNode;

//链栈入栈,相当于链表的头插法
Status Push(LinkStack &s,SElemType e){
	p = new StackNode;	//生成一个新节点
	p->data = e;
	p->next=s;
	s=p;
	return ok;
}

//链栈的出栈
Status Pop(LinkStack &s,SElemType &e){
	//删除栈顶元素,用e返回其值
	if(s==null) return error;	//栈空
	e=s->data;
	p=s;
	s=s->next;
	delete p;
	return ok;
}

共享栈

举报

相关推荐

0 条评论