c++顺序栈的实现


一.实验目的

     巩固线性表的数据结构的存储方法和相关操作,学会针对具体应用,使用线性表的相关知识来解决具体问题,巩固课堂学习。


实验内容

1.建立一个由n个学生成绩的顺序表,n的大小由自己确定,每一个学生的成绩信息由自己确定,实现数据的对表进行插入、删除、查找等操作。分别输出结果。

这里用顺序栈来实现。


//

//  main.cpp

//  顺序栈

//

//  Created by 梁华建 on 2017/10/12.

//  Copyright © 2017 梁华建. All rights reserved.

//


#include <iostream>


const int StackSize=100;

//

template <class Datatype>

class SeqStack {

private:

    Datatype data[StackSize];

    int top;

public:

    SeqStack(){top=-1;};    //将项顶指针置为-1

    ~SeqStack(){}

    void Push(Datatype x);

    Datatype Pop();

    Datatype GetTop();//取栈顶元素实现

    int Empty(); //判断是否为空

    void printlist(); //打印

};


template <class Datatype>

int SeqStack<Datatype>::Empty()

{

    if (top==-1) {

        return 1;

    }

    else return 0;

}

//入栈操作

template <class Datatype>

void SeqStack<Datatype>::Push(Datatype x)

{

    if (top==StackSize-1) throw "栈空间已满,无法再添加";

        data[++top]=x;

}

//出栈操作

template <class Datatype>

Datatype SeqStack<Datatype>::Pop()

{

    if (top==-1) throw "栈已经为空";

    

        Datatype x;

       x=data[top--];

        return x;

    

}


template <class Datatype>

Datatype SeqStack<Datatype>::GetTop()

{

    if (top==-1) throw "这是空栈";

    return data[top];

        

}

template <class Datatype>

void  SeqStack<Datatype>::printlist()

{

    if (top==-1) throw "这是空栈";

    for (int i=0; i<=top; i++) {

        std::cout<<data[i]<<"\n";

    }

}


int main(int argc, const char * argv[]) {

    SeqStack<int> Student = SeqStack<int>();

    std::cout<<"is empty?"<<Student.Empty();

    for (int i=0; i<10; i++) {

        Student.Push(i);

    }

    std::cout<<"is empty?"<<Student.Empty();

    std::cout<<"The top word is"<<Student.GetTop();

    Student.printlist();

    std::cout<<"Pop the pop word,and it's "<<Student.Pop()<<"\n";

 std::cout<<"The top word is"<<Student.GetTop()<<"\n";

    return 0;

}




实验总结:

这次顺序栈是比较简单的,特点就是先进后出,就像羽毛球筒装羽毛球,每次进栈top节点后移一位,就控制头结点就行。缺点十分明显,插入和删除操作比较麻烦会移动大量元素。


  • 7
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值