数据结构教程—栈的链式存储结构C++类实现

类定义(标头.h):

#pragma once
#include<iostream>
using namespace std;

//结点类
template<class ElemType>
class Node {
public:
	ElemType data;
	Node* next;
};
//栈
template<class ElemType>
class Stack {
	Node<ElemType>* Head;
public:
	Stack();//1.无参构造
	Stack(ElemType a[], int n);//2.有参构造
	~Stack();//3.析构函数

	bool StackEmpty();//4.判空
	void Push(ElemType e);//5.进栈,链式结构不考虑栈满情况
	bool Pop(ElemType& e);//6.出栈
	bool GetTop(ElemType& e);//7.取栈顶元素
	void DispStack();//8.输出栈
};

类中各函数的实现代码(源.cpp):

#include"标头.h"

//1.无参构造
template<class ElemType>
Stack<ElemType>::Stack() {
	Head = new Node<ElemType>();
	Head.next = NULL;
}
//2.有参构造
template<class ElemType>
Stack<ElemType>::Stack(ElemType a[], int n) {
	Head = new Node<ElemType>();
	Head->next = NULL;
	for (int i = 0; i < n; i++) {
	Node<ElemType>*p= new Node<ElemType>();
	p->data = a[i];
	p->next = Head->next;
	Head->next = p;
	}
}
//3.析构函数
template<class ElemType>
Stack<ElemType>::~Stack() {
	Node<ElemType>* p = Head->next,*q;
	while (p != NULL) {
		q = p->next;
		delete p;
		p = q;
	}
}
//4.判空
template<class ElemType>
bool Stack<ElemType>::StackEmpty() {
	return Head->next == NULL;
}
//5.进栈,链式结构不考虑栈满情况
template<class ElemType>
void Stack<ElemType>::Push(ElemType e) {
	Node<ElemType>* p = new Node<ElemType>();
	p->data = e;
	p->next = Head->next;
	Head->next = p;
}
//6.出栈
template<class ElemType>
bool Stack<ElemType>::Pop(ElemType& e) {
	if (StackEmpty())
		return false;
	Node<ElemType>* p=Head->next;
	e = p->data;
	Head->next = p->next;
	delete p;
}
//7.取栈顶元素
template<class ElemType>
bool Stack<ElemType>::GetTop(ElemType& e) {
	if (StackEmpty())
		return false;
	e = Head->next->data;
}
//8.输出栈
template<class ElemType>
void Stack<ElemType>::DispStack() {
	Node<ElemType>* p = Head->next;
	while (p != NULL) {
		cout << p->data << " ";
		p = p->next;
	}
	cout << endl;
}

测试代码即测试结果:

int main() {
	int a[] = { 1,6,3,2,0,7,9 };
	Stack<int> stack(a, 7);
	stack.DispStack();
	int e=100;
	stack.Push(e);
	cout << e << endl;
	stack.DispStack();
	stack.Pop(e);
	stack.DispStack();
	return 0;
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值