本文共 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_templatestruct 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/