数据结构学习3--栈的实现(c++)

1 栈的定义和运算

—— 只能在一端插入和删除元素的线性表

栈是一种  特殊的线性表

栈仅能在线性表的一端进行操作

栈顶(Top):允许操作的一端

栈底(Bottom):不允许操作的一端





2 栈的常用操作

创建栈

销毁栈

清空栈

进栈

出栈

获取栈顶元素

获取栈的大小


3 栈的顺序存储


 

4 栈的设计

#pragma once
template <class Type>
class SeqStack
{

private:
	int top;	//栈顶位置
	Type *elements;	//数据域
	int max_size;	//最大长度

public:
	Type Push(const Type item);
	Type Pop();
	Type GetTop();
	void Print();
	int MakeEmpty();
	bool IsEmpty();
	bool IsFull();

public:
	SeqStack(int size);
	~SeqStack();
	
};


5 栈的实现

#include "SeqStack.h"
#include <iostream>
using namespace std;

//构造函数
template <class Type>
SeqStack<Type>::SeqStack (int size):top(-1),max_size(size)
{
	elements = new Type[size];
	if (elements == NULL)
	{
		cout<<"Application err \n";
		exit(-1);
	}
}

//析构函数
template <class Type>
SeqStack<Type>::~SeqStack(void)
{
	delete []elements;
}



template <class Type>
int SeqStack <Type>:: MakeEmpty()
{
	top =-1;
}

template <class Type>
bool SeqStack<Type>::IsEmpty()
{
	return top ==-1;
}

template <class Type>
bool SeqStack<Type>::IsFull()
{
	return top ==max_size;
}


template <class Type>
Type SeqStack<Type>::Push(const Type item)
{
	if (IsFull())
	{
		cout<<"The stack is full.\n";
		return item;
	}
	elements[++top] = item;
	return item;
}

template <class Type>
Type SeqStack<Type>::Pop()
{
	if (IsEmpty())
	{
		cout<<"There is no elements in the stack\n";
		return NULL;
	}
	return elements[--top];
}

 template <class Type>
 Type SeqStack<Type>::GetTop()
 {
	 if (IsEmpty())
	 {
		 cout<<"There is no elements in the stack\n";
		 return;
	 }
	 return elements[top];
 }

 template <class Type>
 void SeqStack<Type>::Print()
 {
	 if (IsEmpty())
	 {
		 cout<<"There is no elements in the stack\n";
		 return;
	 }
	 for (int i = 0; i<=top; i++)
	 {
		 cout<<"--->"<<elements[i];
	 }
 }


6 测试案例

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "SeqStack.h"
#include "SeqStack.cpp"

using namespace std;



int main()
{
	SeqStack<int> st(10);
	for (int i = 0; i<10; i++)
	{
		st.Push(i);
	}
	st.Print();
	st.Pop();
	st.Pop();
	st.Pop();
	st.Print();
	system("pause");
	return 0;
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值