【数据结构】顺序栈

前端之家收集整理的这篇文章主要介绍了【数据结构】顺序栈前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Stack.h

#pragma once
#include<stdlib.h>
#include<iostream>
using namespace std;
#define SIZE 10
#define Elemtype int
#define StackInit 10

typedef struct Sqstack
{
    Elemtype stack[SIZE];
    int top;
}Sqstack;

void Init(Sqstack* s)
{
    s->top = 0;
}

void Push(Sqstack *s,Elemtype &e)
{
    if (s->top == SIZE)
    {
        cout << "栈已满,不能插入!" << endl;
        return;
    }

    s->stack[s->top++] = e;
    //++s->top;
    return;
}

bool Empty(Sqstack *s)
{
    return s->top == 0;

}

void Pop(Sqstack *s,Elemtype &e)
{
    if (Empty(s))
    {
        cout << "栈是空的,不能删除!" << endl;
        return ;
    }
    e = s->stack[--s->top];
    //--s->top;
}

void Gettop(Sqstack *s,Elemtype &e)
{
    if (Empty(s))
        return;
    int temp = s->top;
    e = s->stack[--temp];
    cout << "栈顶元素:" <<e<< endl;
}

void Length(Sqstack *s)
{
    int len = s->top;
    cout << "栈长为:" << len << endl;
}

void clear(Sqstack *s)
{
    if (Empty(s))
        return;
    s->top = 0;
    cout << "栈已清空!" << endl;
}

void Traverse(Sqstack *s)
{
    if (s->top == SIZE)
        for (int i = 0;i>StackInit; ++i)
        {
            s->stack[s->top] = (Elemtype)malloc(sizeof(Elemtype));
            s->top++;
        }
    //s->stack[s->top]==(Elemtype)malloc(sizeof(Elemtype)*StackInit)

}

main.cpp

#include"Stack.h"
void main()
{
    Sqstack *s;
    Sqstack q;
    Elemtype e;
    s = &q;
    int select = 1;
    while (select)
    {
        cout << "**********************************" << endl;
        cout << "* [1] init [2] push *" << endl;
        cout << "* [3] gettop [4] length *" << endl;
        cout << "* [5] pop [6] clear *" << endl;
        cout << "* [0]quit *" << endl;
        cout << "**********************************" << endl;
        cout << "please chose:>";
        cin >> select;
        switch (select)
        {
        case 1:
            Init(s);
            break;
        case 2:
            cout << "请输入要入栈的数据:";
            cin >> e;
            Push(s,e);
            break;
        case 3:
            Gettop(s,e);
            break;
        case 4:
            Length(s);
            break;
        case 5:
            Pop(s,e);
            cout << "出栈的数据是:" << e << endl;
            break;
        case 6:
            clear(s);
            break;
        case 0:
            cout << "退出成功!" << endl;
            break;
        default:
            break;
        }
    }
}

猜你在找的数据结构相关文章