服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - C++模板实现顺序栈

C++模板实现顺序栈

2021-09-02 16:05老樊Lu码 C/C++

这篇文章主要为大家详细介绍了C++模板实现顺序栈,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

顺序栈:利用一组连续的存储单元依次存放自栈底到栈顶的数据元素;由于栈顶元素是经常变动的,所以附设top指示栈顶元素在顺序表中的位置,同时也需要知道顺序栈存储空间的起始位置,因此还需设定一个base指针用来指示栈空间的起始位置。

一般约定top指针指向栈顶元素的下一个位置,即新数据元素将要插入得位置。

下面我们使用模板简单实现一个顺序栈:

SeqStack.h

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
template<typename Type> class SeqStack{
public:
 SeqStack(int sz):m_ntop(-1),m_nMaxSize(sz){
 m_pelements=new Type[sz];
 if(m_pelements==NULL){
  cout<<"Application Error!"<<endl;
  exit(1);
 }
 }
 ~SeqStack(){
 delete[] m_pelements;
 }
 
public:
 
 void Push(const Type item); //push data
 Type Pop();         //pop data
 Type GetTop() const;    //get data
  void Print();        //print the stack
 void MakeEmpty(){      //make the stack empty
 m_ntop=-1;
 }
 bool IsEmpty() const{
 return m_ntop==-1;
 }
 bool IsFull() const{
 return m_ntop==m_nMaxSize-1;
 }
 
 
private:
 int m_ntop;
 Type *m_pelements;
 int m_nMaxSize;
 
};
 
template<typename Type> void SeqStack<Type>::Push(const Type item){
 if(IsFull()){
 cout<<"The stack is full!"<<endl;
 return;
 }
 m_pelements[++m_ntop]=item;
}
 
template<typename Type> Type SeqStack<Type>::Pop(){
 if(IsEmpty()){
 cout<<"There is no element!"<<endl;
 exit(1);
 }
 return m_pelements[m_ntop--];
}
 
template<typename Type> Type SeqStack<Type>::GetTop() const{
 if(IsEmpty()){
 cout<<"There is no element!"<<endl;
 exit(1);
 }
 return m_pelements[m_ntop];
}
 
template<typename Type> void SeqStack<Type>::Print(){
 cout<<"bottom";
 for(int i=0;i<=m_ntop;i++){
 cout<<"--->"<<m_pelements[i];
 }
 cout<<"--->top"<<endl<<endl<<endl;
}

Main.cpp

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
using namespace std;
 
#include "SeqStack.h"
 
int main(){
 SeqStack<int> stack(10);
 int init[10]={1,2,6,9,0,3,8,7,5,4};
 for(int i=0;i<10;i++){
 stack.Push(init[i]);
 }
 stack.Print();
 
 stack.Push(88);
 
 cout<<stack.Pop()<<endl;
 stack.Print();
 
 stack.MakeEmpty();
 stack.Print();
 
 stack.Pop();
 return 0;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/fanyun_01/article/details/77618385

延伸 · 阅读

精彩推荐