代码写多还是会愈发的顺手。写这个示例时,主要的问题在于实现时节点和链表的表示指针有点混乱,不能够马上的反映出来。革命尚未成功,同志仍需努力啊!
写完之前的代码,停下来看了下别人前面内容的实现过程,对比发现结构还是比较混乱的。本例中将节点用结构体表示,包含两个数据成员,分别是数据域和指针域。然后将栈定义为一个模板类,包含两个私有成员,分别是栈的头指针和栈中元素的个数。将栈的基本功能函数声明在类公有成员。这样整体结构就完善许多。
栈的链式存储结构头文件
template<typename T> //结构体定义节点
struct Node
{
T data;
Node *next;
};
template<typename T>
class chStack
{
private:
Node<T> * top; //栈的头指针(栈顶指针)
int count; //栈的长度
public:
chStack(); //栈的构造函数
bool Push(T &e); //将元素e,压如栈
bool Pop(T &e); //将栈顶元素取出到e
bool isEmpty(); //判断栈是否为空
T &GetTop(); //得到栈的栈顶元素,并返回
int Length() const; //返回栈的长度
};
#pragma once
#ifndef STACK_H_
#define STACK_H_
template<typename T>
struct Node
{
T data;
Node *next;
};
template<typename T>
class chStack
{
private:
Node<T> * top;
int count;
public:
chStack();
bool Push(T &e);
bool Pop(T &e);
bool isEmpty();
T &GetTop();
int Length() const;
};
template<typename T>
chStack<T>::chStack()
{
top = nullptr;
count = 0;
}
template<typename T>
bool chStack<T>::Push(T &e)
{
Node<T> *p = new Node<T>;
p->data = e;
p->next = top;
top = p;
count++;
return true;
}
template<typename T>
bool chStack<T>::Pop(T &e)
{
if (isEmpty())
return false;
else
{
Node<T> * temp = top;
e = top->data;
top = top->next;
count--;
delete temp;
}
return true;
}
template<typename T>
T &chStack<T>::GetTop()
{
if (isEmpty()) {
cout << "The stack is empty!\n";
exit(EXIT_FAILURE);
}
else
return top->data;
}
template<typename T>
bool chStack<T>::isEmpty()
{
return(count == 0);
}
template<typename T>
int chStack<T>::Length() const
{
return count;
}
#endif
栈的链式存储结构示例代码
#include<iostream>
#include<string>
#include"stack.h"
using namespace std;
void main()
{
chStack<string> test;
int tim = 1;
cout << tim <<"# Enter your favorite book name (q to quit): \n";
string book;
while (getline(cin, book)) {
if (book == "q")
break;
else
test.Push(book);
tim++;
cout << tim << "# Enter your favorite book name (q to quit): \n";
}
cout << "\nThe number of the stack element is: ";
cout << test.Length() << endl;
cout << "The top of the stack is: ";
cout << test.GetTop() << endl;
int num = test.Length();
string out;
for (int i = 0; i < num; i++) {
if (test.Pop(out)) {
cout << "\nPop element " << out << endl;
cout << "The number of the stack element is: ";
cout << test.Length() << endl;
}
}
}