博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
栈的链式存储结构基本功能实现(C++)
阅读量:4049 次
发布时间:2019-05-25

本文共 2272 字,大约阅读时间需要 7 分钟。

代码写多还是会愈发的顺手。写这个示例时,主要的问题在于实现时节点和链表的表示指针有点混乱,不能够马上的反映出来。革命尚未成功,同志仍需努力啊!

写完之前的代码,停下来看了下别人前面内容的实现过程,对比发现结构还是比较混乱的。本例中将节点用结构体表示,包含两个数据成员,分别是数据域和指针域。然后将栈定义为一个模板类,包含两个私有成员,分别是栈的头指针和栈中元素的个数。将栈的基本功能函数声明在类公有成员。这样整体结构就完善许多。

栈的链式存储结构头文件

template
//结构体定义节点struct Node{
T data; Node *next;};template
class chStack{
private: Node
* 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
struct Node{
T data; Node *next;};template
class chStack{
private: Node
* top; int count;public: chStack(); bool Push(T &e); bool Pop(T &e); bool isEmpty(); T &GetTop(); int Length() const;};template
chStack
::chStack(){
top = nullptr; count = 0;}template
bool chStack
::Push(T &e){ Node
*p = new Node
; p->data = e; p->next = top; top = p; count++; return true;}template
bool chStack
::Pop(T &e){ if (isEmpty()) return false; else { Node
* temp = top; e = top->data; top = top->next; count--; delete temp; } return true;}template
T &chStack
::GetTop(){ if (isEmpty()) { cout << "The stack is empty!\n"; exit(EXIT_FAILURE); } else return top->data;}template
bool chStack
::isEmpty(){ return(count == 0);}template
int chStack
::Length() const{ return count;}#endif

栈的链式存储结构示例代码

#include
#include
#include"stack.h"using namespace std;void main(){
chStack
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; } }}

转载地址:http://esyci.baihongyu.com/

你可能感兴趣的文章
android中对于非属性动画的整理
查看>>
一个简单的TabLayout的使用
查看>>
ReactNative使用Redux例子
查看>>
Promise的基本使用
查看>>
coursesa课程 Python 3 programming 统计文件有多少单词
查看>>
coursesa课程 Python 3 programming 输出每一行句子的第三个单词
查看>>
Returning a value from a function
查看>>
coursesa课程 Python 3 programming Functions can call other functions 函数调用另一个函数
查看>>
coursesa课程 Python 3 programming The while Statement
查看>>
course_2_assessment_6
查看>>
coursesa课程 Python 3 programming course_2_assessment_7 多参数函数练习题
查看>>
coursesa课程 Python 3 programming course_2_assessment_8 sorted练习题
查看>>
在unity中建立最小的shader(Minimal Shader)
查看>>
1.3 Debugging of Shaders (调试着色器)
查看>>
关于phpcms中模块_tag.class.php中的pc_tag()方法的含义
查看>>
vsftp 配置具有匿名登录也有系统用户登录,系统用户有管理权限,匿名只有下载权限。
查看>>
linux安装usb wifi接收器
查看>>
多线程使用随机函数需要注意的一点
查看>>
getpeername,getsockname
查看>>
让我做你的下一行Code
查看>>