栈的链式存储结构基本功能实现(C++)

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

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

栈的链式存储结构头文件

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;
		}
	}
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值