类定义(标头.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;
}